Weird Arrays.asList in Java!

and the other way around!

Person.java
package biz.tugay;
 
public class Person {
 
    private String name;
 
    public Person(String name) {
        this.name = name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}

And the testing class ArraysAsListTest.java
package biz.tugay;
 
import java.util.Arrays;
import java.util.List;
 
public class ArraysAsListTest {
 
    public static void main(String[] args) {
        Person[] persons = new Person[2];
        persons[0] = new Person("Koray");
        persons[1] = new Person("Ahmet");
 
        final List<Person> personList = Arrays.asList(persons);
        System.out.println(personList);
 
        persons[0].setName("Hicran");
        System.out.println(personList);
 
        personList.add(new Person("Hello"));
    }
}

What is the output?
[Person{name='Koray'}, Person{name='Ahmet'}]
[Person{name='Hicran'}, Person{name='Ahmet'}]
 
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.util.AbstractList.add(AbstractList.java:148)
 at java.util.AbstractList.add(AbstractList.java:108)
 at biz.tugay.ArraysAsListTest.main(ArraysAsListTest.java:26)

Weird, isn 't it.. Here is a good answer from StackOverflow related to what is going on in here..

You promised the other way around?


ListToArrayTest.java
package biz.tugay;
 
import java.util.ArrayList;
 
public class ListToArrayTest {
 
    public static void main(String[] args) {
        final ArrayList<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Koray"));
        personList.add(new Person("Tugay"));
 
        final Object[] persons = personList.toArray();
        for (Object personObject : persons) {
            final Person person = (Person) personObject;
            System.out.println(person);
        }
 
        // Modify the list..
        personList.get(0).setName("Ahmet");
 
        // Will the array change?
        for (Object personObject : persons) {
            final Person person = (Person) personObject;
            System.out.println(person);
        }
    }
}

And the output?
Person{name='Koray'}
Person{name='Tugay'}
Person{name='Ahmet'}
Person{name='Tugay'}

So?

So be careful and remember that these arrays and Lists seem to be tightly coupled!