同时对两个 arrayList 进行排序 [英] Sort two arrayLists concurrently

查看:40
本文介绍了同时对两个 arrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个 ArrayList:

Say I have two ArrayLists:

name: [Four, Three, One, Two]
num:  [4, 3, 1, 2]

如果我这样做:Arrays.sort(num),那么我有:

If I do: Arrays.sort(num), then I have:

name: [Four, Three, One, Two]
num:  [1, 2, 3, 4]

有什么办法可以对 num 进行排序并将其反映在名称中,以便我最终得到:

Is there any way I can possibly do a sort on num and have it reflected in name as well, so that I might end up with:

name: [One, Two, Three, Four]
num:  [1, 2, 3, 4]

?请帮帮我.我想到了比较器和对象,但几乎不了解它们.

? Please do help me out. I thought of Comparators and Objects, but barely know them at all.

推荐答案

你应该以某种方式关联 namenum 字段到一个类中然后有该特定类的实例列表.在这个类中,提供一个 compareTo() 方法来检查数值.如果您对实例进行排序,那么名称字段也将按照您想要的顺序排列.

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<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 could be like 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);

    for (Entity entity : entities)
        System.out.print(entity.num + " => " + entity.name + " ");
}

输出:

1 => 一个 2 => 两个 3 => 三个 4 => 四

1 => One 2 => Two 3 => Three 4 => Four

这篇关于同时对两个 arrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆