Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ClassCastException while using Collections. sort(Vector,Comparator)  RSS feed

 
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
sort();
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();
else
return(“ ” ;
}
please help,
thanx in advance,
regards,
apurva
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Apruva,
I made up my own Product class in the code below and I used getElement instead of get and I had no problems using your code. Compare it with your own and you might find your problem.

Regards,
Manfred.
 
apurva mehta
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx manfred,
first of all I tried the same code by writing small class same as yours & it worked fine so i implemented in my real implementation class. But it still gives me classCastException i am not able to understand it why??? Actually my Product class is a stateless session bean(hope u know EJB)
so actually i am storing a remote reference i.e(product)in my vector.But i dont think this should be a problem...
please help....
regards,
Apurva....
 
apurva mehta
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please help help !!!
regards
apurva
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!