简体   繁体   中英

Another way to convert ArrayList containing Strings to an array of Strings in Java?

I have checked the following stackoverflow source to solve my problem:

StackOverflow link

but, when applying the top solution, I still get an error, as follows:

My list is defined here:

List linhaInicial = new ArrayList();

My convertion is made here:

String[] convertido = linhaInicial.toArray(new String[linhaInicial.size()]);

The problem is I still get the following error:

Error:(86, 59) java: incompatible types
required: java.lang.String[]
found:    java.lang.Object[]

My conversion is somehow still returning Object[] when it should now be returning String[] .

Any solutions?

Thanks!

Do not use raw types !

List linhaInicial = new ArrayList();

should be

List<String> linhaInicial = new ArrayList<>();

Change :

List linhaInicial = new ArrayList(); // can contain any Object. 
             //So compiler throws an error while converting an Object to String.

to

List<String> linhaInicial = new ArrayList<String>(); // using Generics ensures
                          //that your List can contain only Strings, so, compiler
                            //will not throw "incompatible types" error

Always try to include the type of the list element in your declaration:

List<String> linhaInicial = new ArrayList<String>();

Avoid raw types as much as possible.

You have to change

List linhaInicial = new ArrayList(); // you are using raw type List

To

List<String> linhaInicial = new ArrayList();// you have to use String type List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM