Home > front end >  If the addresses are different, how is the list updated together?
If the addresses are different, how is the list updated together?

Time:01-04

There are some parts that I do not understand well while studying the list.

I created a new list using Collections.unmodifiableList(list).

And I added an item to the previous list, and the item was also added to the newly created list.

I obviously thought the new list was returned, pointing to a different address, and I thought it was separate, but the result was completely different.

As in the image, the address of the debugging result is different as @829 (old list) and @830 (newly created list).

What happened?


fun main() {
    val list = arrayListOf(Student(), Student(), Student())
    val test = Collections.unmodifiableList(list)

    list.add(Student()) // Student is added along with test
}

class Student() { }

enter image description here

CodePudding user response:

The docs of that method says that it creates a “view” of the other List. That means it is a wrapper around the other List used to prevent consumers of it from using the mutating methods. Since it is a wrapper, it has a distinct memory address. Since it is a view, it will always show the latest changes to the original List that it is referencing.

To get what you want, you need to copy the List which you can do in Kotlin by using toList().

CodePudding user response:

Collections.unmodifiableList returns a wrapper that doesn't allow modifications. It doesn't make a defensive copy, that that's why you see this behaviour.

From the javadocs (the key is the word view):

Returns an unmodifiable view of the specified list [...]

  •  Tags:  
  • Related