Thanks for your help. It works.
public class
Test {
public static void main(
String[] args) {
List ll = new ArrayList();
ll.add(new ICPair(28, 'h'));
ll.add(new ICPair(29, 'c'));
ll.add(new ICPair(2, 'a'));
ll.add(new ICPair(3, 'b'));
ll.add(new ICPair(5, 't'));
ll.add(new ICPair(8, 'p'));
ll.add(new ICPair(99, 'm'));
Object[] data = ll.toArray();
Arrays.sort(data);
System.out.println("AFTER:");
for (int i = 0; i < data.length; ++i) {
System.out.println("" + ((ICPair)data[i]).getId() + " : " + ((ICPair)data[i]).getC() );
}
}
}
import java.util.Arrays;
public class ICPair implements Comparable {
private int id;
private char c;
public ICPair(int i, char c) {
this.id = i;
this.c = c;
}
/** required by Comparator interface */
public int compareTo(Object obj) {
int ret = 0;
if (obj instanceof ICPair) {
ICPair other = (ICPair) obj;
if (id < other.id) {
ret = -1;
} else if (id > other.id) {
ret = 1;
}
} else {
throw new ClassCastException();
}
return ret;
}
public boolean equals(Object other) {
boolean ret = false;
if (other instanceof ICPair) {
ret = compareTo(other) == 0;
}
return ret;
}
/**
* Returns the c.
* @return char
*/
public char getC() {
return c;
}
/**
* Returns the id.
* @return int
*/
public int getId() {
return id;
}
/**
* Sets the c.
* @param c The c to set
*/
public void setC(char c) {
this.c = c;
}
/**
* Sets the id.
* @param id The id to set
*/
public void setId(int id) {
this.id = id;
}
}
Originally posted by bob morkos:
I have an int id (random number e.g.:28,29,14,25,11,3) associated to an Object Animal(). I need to sort the id and retrieve the Animal associated to the ID. Can somoene help by showing an example. Thanks in advance.