简体   繁体   English

Java,使用比较器对 ArrayList 进行排序

[英]Java, Sorting an ArrayList by using Comparator

As I used Comparator for sorting a library after the author's name, I just coincidentally "found" something, which actually works perfectly, but I don't understand why.当我使用 Comparator 在作者姓名之后对库进行排序时,我只是巧合地“发现”了一些东西,它实际上工作得很好,但我不明白为什么。 Firstly please have a look at my code:首先请看一下我的代码:

public class Bookshelf{
        
    Collection<Literature> shelf = new ArrayList<Literature>();
    ArrayList<Literature> unsorted = (ArrayList<Literature>)shelf;

    public void printShelf() {
        Comparator<Literature> compareBySurname= new Comparator<Literature>() {
            @Override
            public int compare(Literature o1, Literature o2) {
                return o1.author.surname.compareTo(o2.author.surname);
                
            }
        };
        
        unsorted.sort(compareBySurname);
          for (Literature c : shelf)
                System.out.println(c);
    }
}

As you can see, I am sorting the ArrayList "unsorted".如您所见,我正在对“未排序”的ArrayList排序。 But after I sort it, I am iterating through the Collection "shelf" and printing the elements of the Collection "shelf".And the output is a list of sorted elements by surname.但是在我对它进行排序之后,我正在遍历集合“架子”并打印集合“架子”的元素。输出是按姓氏排序的元素列表。

To achive my intention, I actually should iterate through the ArrayList "unsorted" and print the elements (of course this option works too).为了实现我的意图,我实际上应该遍历“未排序”的ArrayList并打印元素(当然这个选项也有效)。 So my question is, why the first methode actually works too?所以我的问题是,为什么第一种方法实际上也有效? :D So I am not sorting the Collection "shelf" directly, but I get a sorted list. :D 所以我没有直接对集合“架子”进行排序,但我得到了一个排序列表。

Thanks in advance!提前致谢!

ArrayList<Literature> unsorted = (ArrayList<Literature>)shelf; does not create a new ArrayList .不会创建新的ArrayList It simply makes unsorted refer to the same ArrayList as shelf .它只是让unsorted引用同一个ArrayListshelf They are not different objects.它们不是不同的对象。 You want something like你想要类似的东西

ArrayList<Literature> unsorted = new ArrayList<>(shelf); // <-- a different List.

Because both lists share the same memory reference when you assign the list with the "=" operator.因为当您使用“=”运算符分配列表时,两个列表共享相同的内存引用。 To have a new list with another reference, you must use the key name "new".要使用另一个引用创建新列表,您必须使用键名“new”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM