How to convert an array to a List in Java? I keep getting errors
Hello everyone! I'm a beginner in Java and can't figure out how to convert an array to a list. I need to pass an array of strings to a method that accepts `List`, but something keeps going wrong.
Here's my code:
```java
String[] array = {"apple", "banana", "cherry"};
List list = (List) array; // Compilation error: cannot cast
```
Then I tried using `Arrays.asList()`:
```java
List list = Arrays.asList(array);
list.add("orange"); // Throws UnsupportedOperationException!
```
Why doesn't `Arrays.asList()` allow adding elements? I read that it returns a list, but it behaves strangely. I've also heard about `ArrayList` and `Collections.addAll()`, but I don't understand which approach is correct and what the differences are.
Please advise, how
No answers yet.
Log in to leave an answer