Java:泛型数组创建

3
我正在编写自定义地图,它有自定义的Pair数组,并且地图使用Pair进行操作。它们是通用的,我不知道它们的类型,可能是整数、字符串或双精度浮点数。因此,我不能使用ArrayList,这对我来说是禁止的。
public class FMap<K, V> {
   private FPair<K, V>[] data;
   int capacity=23;
   int used=0;

   public FMap(int cap){
      super();
      capacity=cap;
      used =0;
      data = new FPair[ capacity];
      for(int i=0; i< data.length; ++i)
          data[i] = new FPair<K, V>();
}

但编译器报错:

javac -g -Xlint BigramDyn.java
./TemplateLib/FMap.java:23: warning: [rawtypes] found raw type: FPair
        data = new FPair[capacity];
                   ^
  missing type arguments for generic class FPair<A,B>
  where A,B are type-variables:
    A extends Object declared in class FPair
    B extends Object declared in class FPair
./TemplateLib/FMap.java:23: warning: [unchecked] unchecked conversion
        data = new FPair[capacity];
               ^
  required: FPair<K,V>[]
  found:    FPair[]
  where K,V are type-variables:
    K extends Object declared in class FMap
    V extends Object declared in class FMap
2 warnings

如果我使用 data = new FPair<K, V>[capacity] 而不是 data = new FPair[capacity]

编译器会提示:

TemplateLib/FMap.java:23: error: generic array creation
        data = new FPair<K,V>[capacity];
               ^
1 error

在map的等价函数中: 我正在做: FMap
FMap<K,V> otherPair = (FMap<K,V>) other;

但编译器报错:
./TemplateLib/FMap.java:34: warning: [unchecked] unchecked cast
            FMap<A,B> otherPair = (FMap<A,B>) other;
                                                ^
  required: FMap<A,B>
  found:    Object
  where A,B are type-variables:
    A extends Object declared in class FMap
    B extends Object declared in class FMap
1 warning

1
可能是编译错误:泛型数组创建的重复问题。 - Seelenvirtuose
1个回答

0
请使用ArrayList,如下所示:
List<FPair<K, V>> data = new ArrayList<>(capacity);

由于ArrayList包装了一个数组,因此您既拥有List的所有便利性,又具备数组的功能。

只有在存在数据时才填写项目,不需要new FPair<K, V>();


由于不允许使用ArrayList:

    data = (FPair<K, V>[]) new FPair<?, ?>[10];

<?, ?><Object, Object> 将满足编译器(不再使用原始类型 FPair)。滥用/强制转换是不幸的。但由于类型被剥离,实际上没有区别。

如果您想填充每个项(不建议):

    Arrays.fill(data, new FPair<K, V>());

    Arrays.setAll(data, ix -> new FPair<K,V>());

第一个函数在每个位置上填充相同的元素,当FPair没有改变但可以共享时非常有用:当它是“不可变”的时候。

第二个函数只是一种花式循环的方式。


非常感谢,但我不能使用这个,因为这对我是被禁止的。我的代码运行得很好,但它只给出了一些警告,这意味着我的代码不正确,我不能像这样使用通用数组吗? - Jonathan Cedric
@FurkanYıldız 这个警告并不一定意味着你的代码有错,@SuppressWarnings 在某些情况下是完全可以接受的(主要是与泛型有关)。 - Salem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接