Having trouble adding to ArrayList. I have to convert the normal array to an arraylist.
16.01 Assignment Instructions
Instructions: For this assignment, you are going to use traversal methods.
1. Create a folder called 16.01 Assignment in your module 16 assignments folder.
2. Create a class called Candidate.
a. Candidate will need instance variables name and numVotes (of types String
and int, respectively).
b. Candidate will need appropriate methods and constructors. Make sure to have a
toString() method that prints the name of the Candidate along with the
number of votes.
c. Save the class as Candidate.java.
3. Create a class called TestCandidate and save it as TestCandidate.java.
a. Make sure that you create an array called election. Add the following
Candidates with their votes:
John Smith 5000
Mary Miller 4000
Michael Duffy 6000
Tim Robinson 2500
Joe Ashtony 1800
b. Create a method called printVotes() that traverses through the array and
prints out each element.
c. Create a method called getTotal() that traverses through the array and counts
the total of the votes for all Candidates. It should return that number.
d. Create a method called printResults() that traverses through the array and
creates a table with columns for Candidate name, followed by votes received, and
then percentage of total votes (you can round these values). Note that this method
will need to call getTotal() to use in constructing the third column. After
printing the table, print a line showing the total number of votes for all
e. Test your methods. Your output should be similar to that shown below: 4. Now create a class TestCandidate2 and save it as TestCandidate2.java.
a. Create the same items as for TestCandidate; however, use an ArrayList
b. Output should still look the same as for TestCandidate.
I have done all of this fine. Just the last step is giving me trouble.
Do you mean to convert an array to an ArrayList? Or more precisely add all its elements to a new ArrayList?
I suggest you remember that an ArrayList is a List and a List is a Collection and you can find an ArrayList constructor and a method of the Arrays class. You can do the thing in two stages, but you can write both stages in one line if you so wish. I think I ought not to say any more at the present.
Alternatively you can iterate the array with a loop and add each array element to the ArrayList.
Joined: Oct 13, 2005
Use an enhanced for loop rather than an ordinary for loop to iterate the whole of a List in a read‑only fashion.
Joined: Oct 13, 2005
No, you appear not to have to change an array to a List. I think your technique with add(new Candidate... is a good way to do it.
Have you not come across array initialisers? I shall change some of your code to