1

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?

1

2 Answers 2

2

The code you posted has nothing to do with sorting. The important code is your Personality class. You either:

  1. need to implement Comparable on your class or
  2. create a custom Comparator

Here is an example the shows examples of both approaches:

/*
**  Use the Collections API to sort a List for you.
**
**  When your class has a "natural" sort order you can implement
**  the Comparable interface.
**
**  You can use an alternate sort order when you implement
**  a Comparator for your class.
*/
import java.util.*;

public class Person implements Comparable<Person>
{
    String name;
    int age;

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

    public int getAge()
    {
        return age;
    }

    public String toString()
    {
        return name + " : " + age;
    }

    /*
    **  Implement the natural order for this class
    */
    public int compareTo(Person p)
    {
        return getName().compareTo(p.getName());
    }

    static class AgeComparator implements Comparator<Person>
    {
        public int compare(Person p1, Person p2)
        {
            return p1.getAge() - p2.getAge();
        }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>();
        people.add( new Person("Homer", 38) );
        people.add( new Person("Marge", 35) );
        people.add( new Person("Bart", 15) );
        people.add( new Person("Lisa", 13) );

        // Sort by natural order

        Collections.sort(people);
        System.out.println("Sort by Natural order");
        System.out.println("\t" + people);

        // Sort by reverse natural order

        Collections.sort(people, Collections.reverseOrder());
        System.out.println("Sort by reverse natural order");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by age

        Collections.sort(people, new Person.AgeComparator());
        System.out.println("Sort using Age Comparator");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by descending age

        Collections.sort(people, Collections.reverseOrder(new Person.AgeComparator()));
        System.out.println("Sort using Reverse Age Comparator");
        System.out.println("\t" + people);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

@RamPrakash, that is left up to the OP. The intent of the answer is not to spoon feed the code, but point the OP in the right direction by demonstrating the concept. They should be able to figure out how to customize the code for their particular requirement.
@camickr thanks for your help, but could you please look at the "UPDATE" section of my question, I'm still having problems with my updated code.
@JonathanFrost, You changed your Personality class to create a custom Comparator, but you are not using the Comparator in the sort(...) method. Look at my working example to see how I use the AgeComparator.
1
Collections.sort(rankedList,new Comparator<Personality>(){
                     public int compare(Personality p1,Personality p2){
                           // Write your logic here.
                     }});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.