Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use Comparator in Java to sort
    primarykey
    data
    text
    <p>I learned how to use the comparable but I'm having difficulty with the Comparator. I am having a error in my code: </p> <pre><code>Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable at java.util.Arrays.mergeSort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at java.util.Collections.sort(Unknown Source) at New.TestPeople.main(TestPeople.java:18) </code></pre> <p>Here is my code:</p> <pre><code>import java.util.Comparator; public class People implements Comparator { private int id; private String info; private double price; public People(int newid, String newinfo, double newprice) { setid(newid); setinfo(newinfo); setprice(newprice); } public int getid() { return id; } public void setid(int id) { this.id = id; } public String getinfo() { return info; } public void setinfo(String info) { this.info = info; } public double getprice() { return price; } public void setprice(double price) { this.price = price; } public int compare(Object obj1, Object obj2) { Integer p1 = ((People) obj1).getid(); Integer p2 = ((People) obj2).getid(); if (p1 &gt; p2) { return 1; } else if (p1 &lt; p2){ return -1; } else { return 0; } } } </code></pre> <pre class="lang-java prettyprint-override"><code>import java.util.ArrayList; import java.util.Collections; public class TestPeople { public static void main(String[] args) { ArrayList peps = new ArrayList(); peps.add(new People(123, "M", 14.25)); peps.add(new People(234, "M", 6.21)); peps.add(new People(362, "F", 9.23)); peps.add(new People(111, "M", 65.99)); peps.add(new People(535, "F", 9.23)); Collections.sort(peps); for (int i = 0; i &lt; peps.size(); i++){ System.out.println(peps.get(i)); } } } </code></pre> <p>I believe it has to do something with the casting in the compare method but I was playing around with it and still could not find the solution</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload