Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException while using Collections. sort(Vector,Comparator)

apurva mehta
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wanted to sort a vector which contains the class references,
so I use Collections.sort(vector,Comparator) method.
But I encounter the classCastException while using vector.get(index) method.
I used the same sort logic given in sun tutorial (stated “Solving Common Collections
Problems “ ) and it stated that it wont give any classCastException.
I am using JDK1.3 .
public int populateVector()
// some code which sets the various properties of a class named product ....
//vector is populated with class references
// now I call sort method of this class itself
return vector.size();
public void sort()
// vector containing the class reference is the parameter of sort method.
Collections.sort(vector, new Comparator(){
public int compare(Object o1, Object o2) {
String s1 = (String)((Product)o1).getProdId();
String s2 = (String)(( Product)o2).getProdId ();
int len1 = s1.length();
int len2 = s2.length();
for (int i=0, n=Math.min(len1, len2); i<n; i++) {
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 != c2)
return c1 - c2;
return len1 - len2;
public String getVectorValue(String reqCol, int index)
Product product = new Product();
product = (Product) vector.get(index)
// at the above line I get classCastException.

if(reqCol.equals(“PRODID” )
return (String)product.getProdId();
return(“ ” ;
please help,
thanx in advance,
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic