SandyBites
SandyBites

Reputation: 173

Comparing objects inside an Array for Sorting

I have been trying to compare objects in an Array by one if its properties so that I can sort the objects in the Array into a descending order. Here is the sample code: The array is Candidate[][]

    System.out.println("How many positions for this election? > ");
    numberOfPositions = sc.nextInt();
    Candidate Candidate[][] = new Candidate[numberOfPositions][];
    PoliticalParty Parties[][] = new PoliticalParty[numberOfPositions][];
    for(int i=0;i<numberOfPositions;i++){
        String name;
        String politicalParty;
        System.out.println("Enter position name > ");
        position = sc.next();
        System.out.println("How many seats? > ");
        numberOfSeats = sc.nextInt();
        System.out.println("How many candidates? > ");
        numberOfCandidates = sc.nextInt();
        Candidate[i] = new Candidate[numberOfCandidates+1];
        Candidate[i].sort(votes); //<--------------------------This is what im trying//

Wherein (votes) is an int derived from a text file using this code:

System.out.println("Enter file name > ");
    filename = sc.next();
    try {
        filescan = new Scanner(new File(filename));
    } catch (FileNotFoundException ex) {
        //Logger.getLogger(Election.class.getName()).log(Level.SEVERE, null, ex);
    }
    String L = System.lineSeparator();
    filescan.useDelimiter(L);
    while (filescan.hasNext()) {
        numberOfVoters++;
        line = filescan.next();
        for(int x=0,j=0;j<line.length();j++){
            switch(line.charAt(j)){
                case ',':
                    x++;
                    break;
                case ' ':
                    break;
                default:
                    int y = line.charAt(j)-48;
                    //Integer.parseInt(line.charAt(j).toString());
                    Candidate[x][y].addVote();
                    break;
            }
        }

Wherein (vote) is encapsulated in another Class:

public class Candidate{
int votes = 0;
String politicalParty;

public Candidate(String name, String politicalParty) {
    super(name);
    this.politicalParty = politicalParty;
}

public void addVote() {
    this.votes++;
    //return votes;
}

public int getVotes() {
    return votes;
}

@Override
public String getName() {
    return getName();
}

public void displayFields(){
    System.out.println(this.getName() + " (" + getPoliticalParty() + ") - " + votes);
}

public String getPoliticalParty() {
    return politicalParty;
}

public void setPoliticalParty(String politicalParty) {
    this.politicalParty = politicalParty;
}
}

Upvotes: 0

Views: 128

Answers (4)

Rainbolt
Rainbolt

Reputation: 3660

Arrays have a premade sort method. The Javadoc for Arrays.sort(Object[] a) mentions a "natural ordering". The Comparable interface exists to provide the natural order.

Step 1

Apply the interface to your class.

  • public class Candidate implements Comparable<Candidate> {

Step 2

Implement the compareTo(Candidate c) {} method in your class.

Read the Javadoc for compareTo() contract. In general, it must return a positive, zero, or negative number if this.property is greater than, equal to, or less than c.property, respectively. property is the field upon which you are comparing.

  • Tip: If property is a String, you can simply reuse String's compareTo()
    • return this.property.compareto(c.property);
  • Tip: If property is an integer (like votes), you can cleverly create a positive, zero, or negative number by taking the difference.
    • return this.votes - c.votes;

Step 3

Sort your array.

Now that your object is comparable, call Collections.sort(list) if you have a Collection or Arrays.sort(list) you have an Array of objects.

Upvotes: 1

Pavlo K.
Pavlo K.

Reputation: 371

  1. Why your variable starts from capital letter? It should be like all variables from small.
  2. You should use collections for storing custom data types, then you can easy sort it using Collections.sort(List<T> list, Comparator<? super T> c) and define your own Comparator whatever you want.

Upvotes: 0

JimmyB
JimmyB

Reputation: 12610

Quick question, short answer: java.util.Arrays.sort()

Upvotes: 0

Pablo Lozano
Pablo Lozano

Reputation: 10342

I recommend you to use an ArrayList to store the elements to be sorted and then you'll have 2 options: make your items Comparable (interface) or create a Comparator (interface):

public class Candidate implements Comparable<Candidate> {
    ...

public int compareTo(Candidate c) {
    ... //compare here the attributes of this and c
}

}

Upvotes: 0

Related Questions