简体   繁体   中英

Object[] cannot be converted to Integer[]

Converting a TreeSet object to an array using the toArray method, however I get the error:
Object[] cannot be converted to Integer[]

Here is the code:

public static void main (String[] args) {
    TreeSet elems = new TreeSet<Integer>();
    int[] elemsToAdd = {1,2,3,4};

    for(int i = 0; i < elemsToAdd.length; i++){
        elems.add(elemsToAdd[i]);
    }
    Integer[] elemsArray = elems.toArray(new Integer[elems.size()]);
 }

I've searched other threads for the answer, however all of them recommend to use the toArray method with an Integer array as an argument yet mine still throws an error.

That's due to your usage of raw type. When elems is defined as a raw TreeSet , elems.toArray returns an Object[] , not an Integer[] .

Change

TreeSet elems = new TreeSet<Integer>();

to

TreeSet<Integer> elems = new TreeSet<Integer>();

Erans Answer solves the error but I would also like to make my contribution

TreeSet<T> takes in any Object type, Making it TreeSet<Integer> Would allow you to put Integer values inside the TreeSet, Heres how you can define it

TreeSet<Integer> elems = new TreeSet<>();

You are using a regular loop that can be replaced with a for-each in your case working example is

for (int anElemsToAdd : elemsToAdd) {
   elems.add(anElemsToAdd);
}

And lastly you don't need to define new Integer[elems.size()] with the size defining it as elems.toArray(new Integer[0]) is sufficient

And after all the changes this is the final result

public static void main(String[] args) {
    TreeSet<Integer> elems = new TreeSet<>();
    int[] elemsToAdd = {1, 2, 3, 4};
    for (int anElemsToAdd : elemsToAdd) {
        elems.add(anElemsToAdd);
    }
    Integer[] elemsArray = elems.toArray(new Integer[0]);
}

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