Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Elements to List Java

Tags:

java

Why I am unable to Add element to List after assigning values from to Arrays.asList

List<Integer> sam = Arrays.asList(1,2,3,4);
sam.add(5);

for (Integer integer : sam)
{
  System.out.println(integer);
}
like image 372
Java Beginner Avatar asked Jul 09 '13 10:07

Java Beginner


1 Answers

Arrays.asList(1,2,3,4) creates a "list view" on an array whose size can't change. That way we can use and access an array through the List interface.

If you want a list in which you can add values but still use the convenient Arrays.asList(..), simply do:

List<Integer> sam = new ArrayList<>(Arrays.asList(1,2,3,4));
like image 57
Andreas Dolk Avatar answered Sep 21 '22 06:09

Andreas Dolk