How can I sort a vector of obj according to 1st element of this object

Hello,Suppose I have an object called Obj1 composed of : String val1 - int it1,etc...I have a vector v of Obj1.Now, I would like to sort the vector v but according to the 1st element (val1) of my object (obj1).Is there an easy way of doing it ?THanks
[292 byte] By [celia05esa] at [2007-11-27 0:58:30]
# 1

yeh. java.util.Collections.sort(List, Comparator). you'd need to write a quick comparator for your class, but since you want to sort on Strings anyway, it could just delegate down to that

public class MyClassComparator implements Comparator<MyClass> {

public int compare(MyClass first, MyClass second) {

return first.getVal1().compareTo(second.getVal1());

}

}

....

// later that day

Collections.sort(theVector, new MyClassComparator());

done. obviously I've guessed at class and method names, but you get the picture

georgemca at 2007-7-11 23:32:28 > top of Java-index,Java Essentials,Java Programming...
# 2
Perhaps your object should implement Comparable, and compare based on val1?/ninja'dMessage was edited by: Aleron
Alerona at 2007-7-11 23:32:28 > top of Java-index,Java Essentials,Java Programming...
# 3

> Perhaps your object should implement

> Comparable, and compare based on val1?

>

> /ninja'd

>

> Message was edited by:

> Aleron

heh heh not quite. your solution is slightly different, but no less valid, to mine. I prefer mine, because changing the sort criteria doesn't need any change to the class itself, but it's really down to personal preference

georgemca at 2007-7-11 23:32:28 > top of Java-index,Java Essentials,Java Programming...
# 4

> heh heh not quite. your solution is slightly different, but no less valid, to mine. I > prefer mine, because changing the sort criteria doesn't need any change to

> the class itself, but it's really down to personal preference

And it's a good point too. Should the program want to sort the vector at a later date in regards to a different attribute in the class, your implementation would be the way to go.

Alerona at 2007-7-11 23:32:28 > top of Java-index,Java Essentials,Java Programming...
# 5
THank you so much... I will try it straight away!
celia05esa at 2007-7-11 23:32:28 > top of Java-index,Java Essentials,Java Programming...