TreeMap gives a ClassCastException


General J2EE: TreeMap gives a ClassCastException

  1. TreeMap gives a ClassCastException (3 messages)

    I'm trying to store a Person class object in a TreeMap whose constructor takes a Comparator argument. The comparator compares two persons objects on the basis of first name and stores them. But this gives a ClassCastException. How can I achieve the same. Here is my code: public class Main { public static void main(String[] args) { TreeMap map = new TreeMap(new PersonTest()); map.put("soda", "lime"); map.put("juice", "orange"); map.put("honey", "dabur"); map.put("coke", "coke"); Set set = map.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()){ Map.Entry entry = (Map.Entry); System.out.println(entry.getKey() + "\t" + entry.getValue()); } } } class PersonTest implements Comparator{ private String firstName; private String lastName; /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object aO1, Object aO2) { // TODO Auto-generated method stub PersonTest p1 = (PersonTest)aO1; PersonTest p2 = (PersonTest)aO2; String s1 = p1.firstName; String s2 = p2.firstName; return s1.compareTo(s2); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object aObj) { // TODO Auto-generated method stub String s = (String)aObj; //PersonTest p = (PersonTest)aObj; return compare(this, s)==0; } }
  2. RTFM?
  3. Thnxx!! I re-read the FM and got this time right
  4. No problem. :)