Say I have two ArrayLists:
name: [Four, Three, One, Two]
num: [4, 3, 1, 2]
If I do: Arrays.sort(num), then I have:
name: [
You should somehow associate name
and num
fields into one class and then have a list of instances of that specific class. In this class, provide a compareTo()
method which checks on the numerical values. If you sort the instances, then the name fields will be in the order you desire as well.
class Entity implements Comparable {
String name;
int num;
Entity(String name, int num) {
this.name = name;
this.num = num;
}
@Override
public int compareTo(Entity o) {
if (this.num > o.num)
return 1;
else if (this.num < o.num)
return -1;
return 0;
}
}
Test code could be like this:
public static void main(String[] args) {
List entities = new ArrayList();
entities.add(new Entity("One", 1));
entities.add(new Entity("Two", 2));
entities.add(new Entity("Three", 3));
entities.add(new Entity("Four", 4));
Collections.sort(entities);
for (Entity entity : entities)
System.out.print(entity.num + " => " + entity.name + " ");
}
Output:
1 => One 2 => Two 3 => Three 4 => Four