Languages

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

0 points
Asked by:
Payne
654

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:
Payne
654

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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