2

I am having error when i add elements using list reference which returned by method.

Dummy.java

package firstPro;

import java.util.List;

public class Dummy {

    private List<String> names;

    public Dummy(List<String> names) {
        this.names = names;
    }

    public List<String> getNames() {
        return this.names;
    }

}

main

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class count {

    public static void main(String[] args) {
        Dummy obj = new Dummy(Arrays.asList("foo1", "foo2", "foo3", "foo4", "foo5"));
        List<String> name = obj.getNames();
        name.add("foo6");
        System.out.println(name);

    }

}

Error

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at firstPro.count.main(count.java:13)

I know i can get rid of this error by adding

new ArrayList(obj.getNames())

My Question is why i can't use that referece as raw?

Maroun
  • 94,125
  • 30
  • 188
  • 241
user951215
  • 91
  • 1
  • 8
  • 1
    Note that it's often not desirable to allow users of your class to have direct access to internal state. Returning `Collections.unmodifiableList(names)` allows you to keep control of the contents of that list (although that would also cause an exception to be thrown if you tried to add to it). Better to provide an adder method on your class. – Andy Turner Nov 26 '17 at 09:27
  • tnx for the useful advice sir i will keep it in mind – user951215 Nov 26 '17 at 09:31

3 Answers3

2

From the JavaDoc of Arrays.asList(...), emphasis mine:

Returns a fixed-size list backed by the specified array.

You can make Dummy handle modifications by making it copy the values from the received list into a new ArrayList instance, by changing its constructor:

public Dummy(List<String> names) {
    this.names = new ArrayList<>(names);
}
janos
  • 120,954
  • 29
  • 226
  • 236
2

Arrays.asList("foo1", "foo2", "foo3", "foo4", "foo5") creates a fixed sized list, so you can't add/remove elements to it (only modify the existing elements or replace the elements in the existing indices).

You can use:

new ArrayList<>(Arrays.asList("foo1", "foo2", "foo3", "foo4", "foo5"))

to support adding new elements.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

To quote Arrays.asList's documentation:

Returns a fixed-size list backed by the specified array.

Since the returned List has a fixed-size, it does not support the add operation, and calling it will throw an UnsupportedOperationException as you've noticed.

Mureinik
  • 297,002
  • 52
  • 306
  • 350