I'm pretty new at Java, I've only just started learning it for my Computer Science university course.
I'm writing a program that has an ArrayList that holds Personality objects called individual, declared in a PersonalityList class as such: private ArrayList<Personality> individual;
These Personality objects hold a private field called votes of type int.
I have also declared the same ArrayList in the PersonalityList class but with a different name - rankedList - like so: private ArrayList<Personality> rankedList;
In my program I have made a method called top(int value). In this method, I am trying to look through the individual list using a while loop, obtain objects from that list providing their index number is below the value of the value parameter, add it to the rankedList list, and then sort the rankedList list in order of their votes field, with the object with the highest number of votes coming first in the list (with index: 0). Currently, this is my top method:
public void top(int value)
{
int index = 0;
int listSize = individual.size();
rankedList = new ArrayList<Personality>();
if(value > listSize) {
value = listSize;
}
else {
System.out.println("Error: Enter a positive integer value.");
}
if(listSize > 0) {
while(index < value) {
Personality prsn = individual.get(index);
rankedList.add(prsn);
System.out.println(prsn.getDetails());
index++;
}
}
else {
System.out.println("Error: The array list has no personalities stored inside it.");
}
}
I am currently printing the details of each Personality object obtained by the while loop using a getDetails() method (contains the object fields) defined in the Personality class, simply to check that it obtains the correct number of objects.
I understand that I need to use the Collections.sort functionality from looking at other Stack Overflow posts, but, even after looking through the answers of these posts, I have no idea how to implement it into my code. I have tried but I keep getting errors thrown at me which I don't really understand.
Any help, preferably specific code, would be very much appreciated. Thank you!
UPDATE:
Thanks for the example code @camickr. In my Personality class I added the following code:
static class votesComparator implements Comparator<Personality>
{
public int compare(Personality p1, Personality p2)
{
return p1.getVotes() - p2.getVotes();
}
}
I have also edited my top method in my PersonalityList class to this:
if(listSize > 0) {
while(index < value) {
Personality prsn = individual.get(index);
rankedList.add(prsn);
System.out.println(prsn.getDetails());
index++;
}
Collections.sort(rankedList);
System.out.println("Sort by Natural order");
System.out.println("\t" + people);
}
else {
System.out.println("Error: The array list has no personalities stored inside it.");
}
However now I'm getting an error which states "no suitable method found for sort(java.util.List)", called at Collection.sort(rankedList).
What is the reason for this?