Win a copy of Terraform in Action this week in the Cloud forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Problem in sorting using Comparator

 
Ranch Hand
Posts: 1277
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Tell me where i am going wrong. My goal is to sort the objects in 'set'(a TreeSet)
of class 'Person2' as per the ints passed into addNumber and finally output them
The code is compiling fine( with some warnings), but i am getting a ClassCastException in the compare() method.

Please give me the modifications in the code.

//this is modifiedTreeSet2.java

import java.util.*;


class modifiedTreeSet2 implements Comparator {

modifiedTreeSet2() { }

public int compare(Object o1,Object o2) {
Person2 p1=(Person2)o1;
Person2 p2=(Person2)o2;
return new Integer(p1.num1).compareTo(new Integer(p2.num1));
}
public String toString(Person2 p) {
return new Integer(p.num1).toString();

}

public static void main(String args[]) {

Set set=new TreeSet(new modifiedTreeSet2());
set.add(Person2.addNumber(2));
set.add(Person2.addNumber(3));
Iterator it=set.iterator();
while(it.hasNext()) {
System.out.println(it.next()+" ");
}
}


}


//this is Person2.java

public class Person2 {
static int num1;
static void addNumber(int num) {
num1=num;
}
}
 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


1.You're not adding Person2 objects to your Treeset here, but the result of the operation addNumber() (Are you sure that addNumber is declared as you posted it ??)

2. Why is your num1 field in Person2 static ?
If num1 is static, p1.mum1 will always be equals to p2.num1 (in the compare method) because p1.num1 == Person2.num1 == p2.num1
So new Integer(p1.num1).compareTo(new Integer(p2.num1)) will always return 0.
reply
    Bookmark Topic Watch Topic
  • New Topic