Sort two arrayLists concurrently

前端 未结 4 1634
春和景丽
春和景丽 2021-01-07 11:38

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: [         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 12:03

    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

提交回复
热议问题