Array.asList method returns List as output. Although this list is mutable, this is in a fixed size. So if we try to modify it by adding more elements it will throw an error.
Hence one of the solutions to overcome that is to pass the result of Array.asList to a new ArrayList constructor, which will return mutable and dynamic size ArrayList.
// fixed size mutable list
var m = Arrays.asList(Arrays.stream(x).boxed().toArray(Integer::new));
// m.add(3); // doesnt work
// mutable non-fixed size mutable list
var l = new ArrayList<>(Arrays.asList(Arrays.stream(x).boxed().toArray(Integer::new)));
In this article, we explore different approaches to convert an array to a list in java.
We also discuss how we can get mutable and immutable lists from primitive arrays.
Before You Leave
Let me know if I can be of any help to your career, I would love to chat or jump on a call. you can connect me over Linkedin.