Initializing ArrayList in one line in Java: how to create and fill a list immediately
Hello everyone! I just started learning Java and encountered this problem. I need to create an ArrayList and immediately fill it with several values. In Python, I can write `my_list = [1, 2, 3]` and it's done. But in Java, I see this code:
```java
ArrayList list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");
```
This takes three lines, and if there are many elements, the code becomes cumbersome. I tried writing something like `ArrayList list = {"one", "two", "three"};`, but the compiler complains. Then I found that you can use `Arrays.asList(...)`, but it returns some other type, not ArrayList. When I try to add or remove an element from such a list, I get `UnsupportedOperationException`.
Tell me how to properly initialize
No answers yet.
Log in to leave an answer
Blogs
Deploying a Swift Application on VPS: Step-by-Step Guide