【问题标题】:Issue with sorting in a list of unequal size在大小不等的列表中排序的问题
【发布时间】:2012-09-11 15:02:38
【问题描述】:

我在给定类中排序时遇到问题,数据没有得到排序,这里两个列表的大小不相等,但列表在 list1 中存在键。FP 是一个具有键和值成员的 bean 类。数据未排序。我希望 list1 以相同的顺序在列表末尾附加额外的键

public class MyList {

    public static void main(String[] args) {
        FP f = new FP();
        f.setKey("s");
        f.setValue("he");
        FP f1 = new FP();
        f1.setKey("t");
        f1.setValue("she");
        List<FP> list = new ArrayList<FP>();
        list.add(f);
        list.add(f1);
        FP f2 = new FP();
        f2.setKey("t");
        f2.setValue("he");
        FP f3 = new FP();
        f3.setKey("s");
        f3.setValue("she");
        FP f4 = new FP();
        f4.setKey("u");
        f4.setValue("she");
        List<FP> list1 = new ArrayList<FP>();
        list1.add(f2);
        list1.add(f3);
        list1.add(f4);
        final Map<FP, Integer> indices = new HashMap<FP, Integer>();
        for (int i = 0; i < list.size(); i++) {
            indices.put(list.get(i), i);
        }
        Collections.sort(list1, new Comparator<FP>() {
            public int compare(FP o1, FP o2) {
                int index1 = (Integer) (indices.containsKey(o1) ? indices
                        .get(o1) : +1);
                int index2 = (Integer) (indices.containsKey(o2) ? indices
                        .get(o2) : +1);
                return index1 - index2;
            }

        });

        for (int i = 0; i < list1.size(); i++) {
            System.out.println("the data is" + list1.get(i).getKey());
        }

    }
}

【问题讨论】:

    标签: java sorting collections arraylist


    【解决方案1】:

    我猜您的问题与 FP 对象没有覆盖 equals()hashCode() 方法有关,因为 (indices.containsKey(o1)) 可能返回 false。

    当您使用对象作为集合的内容并希望使用诸如contains()(或)get(object) 之类的调用进行查找时,如果您不覆盖equals()hashCode(),则查找可能会失败。

    例子:

    Set<FP> keySet=indices.keySet();
    Iterator<FP> keySetIter = keySet.iterator();
    while(keySetIter.hasNext())
    {
    FP fpObj = keySetIter.next();
    //Write your equality condition here.
    }
    

    【讨论】:

    • public boolean equals(Object obj) { // TODO 自动生成的方法存根 return super.equals(obj); } @Override public int hashCode() { // TODO 自动生成的方法存根 return super.hashCode(); }
    • 但是 contains 方法给我一个错误,请用我的例子解释
    • 包含方法?我在你的代码中没有看到。发布错误消息。
    • 我不想在我的 POJO 类中使用 equals 和 hashcode,我怎样才能使代码使用 contains 方法它不适合我
    • 正如我所说,如果您不覆盖 equals() 并且 hashcode() 包含它,则不能保证其行为符合预期。一种方法可能是,每次循环地图以检查对象。但是,这很昂贵。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2011-08-26
    • 2019-08-20
    • 1970-01-01
    • 2012-07-04
    • 2011-11-13
    相关资源
    最近更新 更多