如何实例化Map.Entry< K,V>数组在Java? [英] How do you instantiate a Map.Entry<K, V> array in Java?
问题描述
可能重复:
Java泛型:包含泛型的数组
类,它包含从数组中添加和删除元素的两种方法。为了使它通用,它需要一个子类型,所以它应该能够处理不同类型的对象。
问题是,当我实例化使用MapEntry java.util.Map.Entry的实现)作为子类型。这导致在尝试将对象数组转换为MapEntry数组时抛出ClassCastException。我猜这是因为以下行(其中T是子类型):
array =(T []) (new Object [array.length + 1]);
array =(T [])(new Object [array.length - 1]);
分别用于将数组大小增加/减少1。我也使用这个在整数,字符串和对象的数组,它的工作正常与那些。
此外,它明确表示,我需要使用数组,没有列表等。
有没有办法解决这个问题,同时仍然保持类作为通用的可能?
编辑:管理以解决问题。这里是工作代码:
array =(T [])Array.newInstance(array.getClass()。getComponentType array.length + 1);
array =(T [])Array.newInstance(array.getClass()。getComponentType(),array.length - 1);感谢所有的帮助:D
$ b >解决方案 A)不使用数组,他们是可怕的。使用集合。
B)不能在不知道数组类型的情况下创建通用数组。如果你有类型(类),你可以做:
T [] array = Array.newInstance长度);
阅读:
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
解决方案 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:
这篇关于如何实例化Map.Entry< K,V>数组在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!