【问题标题】:Java: Generic Array CreationJava:通用数组创建
【发布时间】:2017-01-06 12:34:24
【问题描述】:

我正在编写我的自定义 Map,它具有自定义 Pair 数组,并且 Map 使用该对进行操作。

它们是通用的,我不知道它们的类型,它可以是整数、字符串或双精度。所以我不能使用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&lt;K, V&gt;[capacity] 而不是data = new FPair[capacity]

编译器说:

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

--

在地图的同等功能中: 我正在做: 地图

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

【问题讨论】:

标签: java


【解决方案1】:

这样使用 ArrayList:

List<FPair<K, V>> data = new ArrayList<>(capacity);

由于 ArrayList 包装了一个数组,因此您拥有 List 的所有舒适性和数组的功能。

只有有数据时才填一项,没有new FPair&lt;K, V&gt;();


不允许使用 ArrayList:

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

&lt;?, ?&gt;&lt;Object, Object&gt; 将满足编译器的要求(不再是使用的原始类型 FPair)。虐待/演员是不幸的。但由于类型被剥离,实际上并没有区别。

如果你想填写每一项(不建议):

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

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

第一个在每个位置填充 same 元素,当 FPair 未更改但可以共享时很有用:当它是“不可变的”时。

第二种只是一种奇特的循环方式。

【讨论】:

  • 非常感谢,但我不能使用它,因为它对我来说是被禁止的。我的代码按照我的意愿运行,但它只给出一些警告,这意味着我的代码不正确,我不能像它一样使用泛型数组吗?
  • @FurkanYıldız 警告并不一定意味着您的代码错误,@SuppressWarnings 在某些情况下完全可以接受(主要是泛型)
猜你喜欢
  • 2012-05-27
  • 2012-03-28
  • 2014-06-19
  • 2012-04-19
  • 1970-01-01
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多