Languages

Java - Error: java: incompatible types: java.lang.Object[] cannot be converted to java.lang.String[] - convert ArrayList to String[]

0 points

I tried converting an ArrayList to an array of strings (String []) and got this error:

java: incompatible types: java.lang.Object[] cannot be converted to java.lang.String[]

My code: 

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        List<String> arrayList = new ArrayList<>();
        arrayList.add("x");
        arrayList.add("y");

        String[] strings = arrayList.toArray();  // this line throw an error 
    }
}
1 answer
0 points
Answered by:
Dirask Admin - Marwin
1430

I found a solution - It needs to change

String[] strings = arrayList.toArray(); 

to

String[] text = arrayList.toArray(String[]::new)

I also wrote an article about it - Java - convert ArrayList to array[].

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join