How to use Comparator in Java to sort

Posted by Dan on Stack Overflow See other posts from Stack Overflow or by Dan
Published on 2010-05-15T06:22:07Z Indexed on 2010/05/15 6:24 UTC
Read the original article Hit count: 257

Filed under:
|
|

I learned how to use the comparable but I'm having difficulty with the Comparator. I am having a error in my 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)

Here is my 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 > p2 ){ return 1; } else if (p1 < p2){ return -1; } else return 0; } }

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

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

© Stack Overflow or respective owner

Related posts about java

Related posts about comparator