How to convert an array to ArrayList in Java? Creating ArrayList from array
Hello everyone! I just started learning Java and ran into a problem. I have an array of strings that I get from another method:
```java
String[] fruits = {"Apple", "Banana", "Orange"};
```
I need to pass this array to a method that only accepts `ArrayList`. I tried doing this:
```java
ArrayList list = new ArrayList<>(fruits);
```
But the compiler gives an error: "cannot infer type arguments for ArrayList<>". Then I tried:
```java
ArrayList list = (ArrayList) Arrays.asList(fruits);
```
That doesn't work either — it throws a ClassCastException.
I read that in Java you can't just convert an array to an ArrayList directly. But how do you do it correctly? Is there a simple way to create a mutable list from an array? And why does
No answers yet.
Log in to leave an answer