K
K
KaizerSX2020-02-21 14:57:20
Java
KaizerSX, 2020-02-21 14:57:20

Why is the result like this?

Why are we changing the value of the List object changing the value of the names array?

String [] names = {"Tom", "Dick", "Harry"};
         List<String> list = Arrays.asList(names);
         list.set(0, "Sue");
         System.out.println(names[0]);


result: Sue

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2020-02-21
@KaizerSX

Because it Arrays.asList()returns an Array List instance using the passed array. That is, you simply wrapped the same data with an additional abstraction.

A
Alexey Cheremisin, 2020-02-21
@leahch

Well, because you are not changing the array, but the NEW list obtained from the array, and you do not touch the array itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question