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);
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With