Home > Back-end >  Java, Sorting an ArrayList by using Comparator
Java, Sorting an ArrayList by using Comparator

Time:11-14

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. 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". 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). 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.

Thanks in advance!

CodePudding user response:

ArrayList<Literature> unsorted = (ArrayList<Literature>)shelf; does not create a new ArrayList. It simply makes unsorted refer to the same ArrayList as shelf. They are not different objects. You want something like

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

CodePudding user response:

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".

  • Related