java - Sort two arrayLists concurrently -
say have 2 arraylists:
name: [four, three, one, two] num: [4, 3, 1, 2]
if do: arrays.sort(num), have:
name: [four, three, one, two] num: [1, 2, 3, 4]
is there way can possibly sort on num , have reflected in name well, might end with:
name: [one, two, three, four] num: [1, 2, 3, 4]
? please me out. thought of comparators , objects, barely know them @ all.
you should somehow associate name
, num
fields 1 class , have list of instances of specific class. in class, provide compareto()
method checks on numerical values. if sort instances, name fields in order desire well.
class entity implements comparable<entity> { 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 this:
public static void main(string[] args) { list<entity> entities = new arraylist<entity>(); 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); (entity entity : entities) system.out.print(entity.num + " => " + entity.name + " "); }
output:
1 => 1 2 => 2 3 => 3 4 => four
Comments
Post a Comment