Question

According to the Java documentation,

... two lists are defined to be equal if they contain the same elements in the same order.

Could someone please explain why the following code outputs "They're equal"? I can't understand why both lists are being shuffled.

    unshuffledPlaylist = sqlHelper.findSongs(SQLHelper.NOW_PLAYING_TABLE,
            "", orderBy);
    shuffledPlaylist = unshuffledPlaylist;

    Collections.shuffle(shuffledPlaylist);

    if (shuffledPlaylist == unshuffledPlaylist){
        System.out.println("They're equal");
    }
Was it helpful?

Solution

With

shuffledPlaylist = unshuffledPlaylist;

you are not creating copy of original list, but you are making shuffledPlaylist reference to hold same list as unshuffledPlaylist so in the end they both hold same list. That is why each modification done via one of these references is visible via other reference.

To create separate list based on original list you can use copying constructor

shuffledPlaylist = new ArrayList(unshuffledPlaylist);
Collections.shuffle(shuffledPlaylist);//now you can shuffle copy of original list

Also to check if two List (or any object) instances are equal (have same state) don't use X==Y because == just checks if references X and Y hold same object (like in your case). Instead you should use X.equals(Y) method.

OTHER TIPS

Because you are also shuffling unshuffledPlaylist, since they point to the same reference.

You need to create a new object that contains the content of unshuffledPlaylist.

shuffledPlaylist = new ArrayList<>(unshuffledPlaylist);

The findSongs function creates a list object. This object uses memory and exists in a place in memory, The Heap

The unshuffledPlaylist is a merely a reference to that object. It is not the object itself it is just a way of gaining access to the object on the heap.

The following line of code ...

shuffledPlaylist = unshuffledPlaylist;

creates a new reference called shuffledPlaylist but it also refers to the exact same object on the heap that unshuffledPlaylist refers to.

So it does not matter which reference you use to shuffle that list object.

Both references shuffledPlaylist and unshuffledPlaylist refer to the exact same object.

The meaning of the following statement ...

if (shuffledPlaylist == unshuffledPlaylist){
        System.out.println("They're equal");
}

is

if shuffledPlaylist and unshuffledPlaylist refer to the same object, print out "They're equal"

It would be more accurate to output

System.out.println("shuffledPlaylist and unshuffledPlaylist refer to the exact same object.");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top