• Post Reply Bookmark Topic Watch Topic
  • New Topic

sorting a Vector  RSS feed

 
John Bell
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a Vector of objects. The objects have two fields one a Calender and the other a double. I want to sort on the Calender field and am trying to use a Comparator :-
The Vector data consists of VariteMetrics.
someMethod(Vector data) {
Comparator COMPAREDATES = new Comparator() {
public int compare(Object o1, Object o2){
VariateMetric vm1 = (VariateMetric) o1;
VariateMetric vm2 = (VariateMetric) o2;
return vm1.getTime().before(vm2.getTime())? -1 : vm1.getTime().after(vm2.getTime())? 1 : 0 ;
}
};
Collections.sort(data, COMPAREDATES);
}
 
John Bell
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When this code is run there is ClassCastException
 
Gabriel White
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are typecasting an oject or something that the comparator doesn't like (unComparable). Thus, when your method is supposed to return a comaprator, it dishes out the class cast exc.
Or the method that you are calling is not compiling at runtime due to a method call that returns a value that is not accepted by the other method making the call.
For instance:
public Marble getMarble(){return m};
public Object getDiameter(){
//if this method returns an Oject
then the typecast to a marble object is required.
this is where your's is hanging up:
VariateMetric vm1 = (VariateMetric) o1;
VariateMetric vm2 = (VariateMetric) o2;
o1 and o2 are at runtime not comparable.
[ April 22, 2004: Message edited by: Gabriel White ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!