How to Sort a Collection or a List of tuples?
Hi everybody!!
I have a Collection or a List like:
List<MyClass> list=new ArrayList<MyClass>();
The class MyClass have two atributes: private String info
private int quantity
I want to Sort my class top bottom comparing quantity in order to print the list like:
30000 info
20000 info
...
you know what I mean. I've looked in the api for MyComparator() or Collections.Sort() by I didn't understand their way of work and I got a lot of ununderstanable errors.
Some commented peace of code will help me a lot.
Thanks to all!!!!!!!!!!!
> 5.0
public class MyClass implements Comparable<MyClass> {
public int compareTo(MyClass o) {
//return a negative integer, zero, or a positive integer as
//this object is less than, equal to, or greater than the specified object.
return 0;
}
}
Kaj
The code:
import java.util.*;
class MyClass implements Comparable<MyClass> {
private String id;
private int tresure;
public MyClass(String s,int ie) {
this.id=s;
this.tresure=ie;
}
public int compareTo(MyClass o) {
return 0;
}
}
public class Hola {
public static void main(String[]args) {
Collection<MyClass> proba=new ArrayList<MyClass>();
for(int i=0;i<10;i++) {
proba.add(new MyClass("hola",i));
}
Collections.sort(proba);
}
}
The error:
Hola.java :19: cannot find symbol
symbol:method sort<java.util.collections><MyClass>>
location: class java.util.collections
Collections.sort<proba>;
1error
You may like to refer to the API documentation:
* http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html
List appears to be a sub-interface of Collection; Thus, Collections.sort(Collection) is not allowed, as mentioned by kajbj, it takes List:
* http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html
Hope this makes sense to you.
Cheers,
yc