How do you instantiate a Map.Entry array in Jav

2019-09-02 11:02发布

Possible Duplicate:
Java Generics: Array containing generics

I have a Java class which contains 2 methods which add and remove an element from an array. To make it generic it takes a subtype so it should be able to work on different types of objects.

The problem is that when I instantiate it using MapEntry (where MapEntry is an implementation of java.util.Map.Entry) as the subtype. This results in a ClassCastException being thrown when trying to convert an Object array to a MapEntry array. I'm guessing this is because of the following lines (Where T is the subtype):

array = (T[])(new Object[array.length + 1]);
array = (T[])(new Object[array.length - 1]);

Which are used to increase/decrease the array size by 1 respectively. I also use this on arrays of Integers, Strings and Objects, and it works fine with those.

Also, it's explicitly stated that I need to use arrays for this, so no lists, etc.

Is there any way to get around this problem while still keeping the class as generic as possible?

Edit: Managed to get the problem solved. Here's the working code:

array = (T[])Array.newInstance(array.getClass().getComponentType(), array.length + 1);
array = (T[])Array.newInstance(array.getClass().getComponentType(), array.length - 1);

Thanks for all the help :D

2条回答
Animai°情兽
2楼-- · 2019-09-02 11:20

A T[] array is a subclass of Object[], and you may the cast T[] to Object[]. But the reverse is false: you can't cast an Object[] to T[] because Object[] is not a subclass of T[].

I think your question boils down to How to create an array of a generic type?

查看更多
We Are One
3楼-- · 2019-09-02 11:37

A) don't use arrays, they are awful. Use collections instead.

B) you can't create a generic array without knowing the array type. if you do have the type (the class), you can do:

T[] array = Array.newInstance(type, length);

Read:

查看更多
登录 后发表回答