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?