首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java:泛型数组创建

Java:泛型数组创建
EN

Stack Overflow用户
提问于 2017-01-06 20:34:24
回答 1查看 356关注 0票数 3

我正在编写我的自定义Map,它有自定义的配对数组,Map使用配对进行操作。

它们是通用的,我不知道它们的类型,它可以是整型,字符串或双精度型。所以我不能使用ArrayList,这对我来说是禁止的。

代码语言:javascript
复制
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>();
}

但是编译器说:

代码语言:javascript
复制
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]

编译器说:

代码语言:javascript
复制
TemplateLib/FMap.java:23: error: generic array creation
        data = new FPair<K,V>[capacity];
               ^
1 error

--

在map的等同功能中:我正在做: FMap

代码语言:javascript
复制
FMap<K,V> otherPair = (FMap<K,V>) other;

但是编译器说:

代码语言:javascript
复制
./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
EN

回答 1

Stack Overflow用户

发布于 2017-01-06 21:33:13

按如下方式使用ArrayList:

代码语言:javascript
复制
List<FPair<K, V>> data = new ArrayList<>(capacity);

当ArrayList包装一个数组时,您将拥有List的所有舒适之处和数组的功能。

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

不允许As ArrayList:

代码语言:javascript
复制
    data = (FPair<K, V>[]) new FPair<?, ?>[10];

<?, ?><Object, Object>将满足编译器(不再是原始类型FPair使用的)。辱骂/演员阵容不走运。但是,由于类型被剥离,因此没有实际的区别。

如果你想填写每一项(不可取):

代码语言:javascript
复制
    Arrays.fill(data, new FPair<K, V>());

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

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41505864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档