The inferred type of Arrayylist to Array is toArray () does not match an upper limit error

This is the sinplet code:

Excel excel = new Excel();
ArrayList<Integer> a1=excel.readExcelSheet("C:\\Users\\Madhukar\\Desktop\\Employee.xls");
        System.out.println("Using Iterator");
        Iterator iterator = a1.iterator();
        while (iterator.hasNext()) {
       System.out.println(iterator.next());}
        int x=a1.size();
        int[] a3=new int[x];
        a3=a1.toArray(a3);

      

This error message:

No suitable method found for toArray parameter (int []) AbstractCollection.toArray (T # 1 []) method not applicable (assumed type does not match upper bounds (s) inferred: int upper bound (s): object)

  where T#1,T#2 are type-variable...

      

+3


source to share


2 answers


Primitives and generics are not the same. You will need Integer[]

, not int[]

.



+7


source


Google Guava to the Rescue!

To paraphrase "Google has already done this!"General Disarray

If you ever need to do something, someone at Google might need to do the same at some time and put a really well tested implementation in Guava.

If it's not in Guava, there might be a good reason not to do what you want to do.

JavaDoc Ints.toArray ()

Returns an array containing each value in the collection, converted to int as Number.intValue (). The elements are copied from the set of arguments as if by collection.toArray (). Calling this method is as thread safe as calling this method.



import com.google.common.primitives.Ints;

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

public class ObjectListToPrimitiveArray
{
    public static void main(final String[] args)
    {
        final List<Integer> il = new ArrayList<>();
        il.add(0);
        il.add(1);
        il.add(2);
        il.add(3);

        final int[] ia = Ints.toArray(il);

        System.out.println(Arrays.toString(ia));
    }
}

      

If you are using Guava it is better to use the built-in list constructor

public static void main(final String[] args)
{
    final List<Integer> il = ImmutableList.<Integer>builder()
            .add(0)
            .add(1)
            .add(2)
            .add(3).build();

    final int[] ia = Ints.toArray(il);

    System.out.println(Arrays.toString(ia));
}

      

Both outputs:

[0, 1, 2, 3]

      

+4


source







All Articles