繁体   English   中英

如何创建具有两个泛型类型的类的实例?

[英]How do I create an instance of a class with two generic types?

我正在尝试创建一个类ZipIterator的实例,该实例将两个任意数组作为参数,并通过构造函数将它们设置为等于两个私有字段K []和V []。 在我的Testing类的主要方法中,我正在写

import java.util.Iterator;

public class ZipIterator<K,V>
{
    private K[] arr1;
    private V[] arr2;
    private int pos = 0;

    public ZipIterator(K[] arr1, V[] arr2) {
        this.arr1 = arr1;
        this.arr2 = arr2;
    }

}

在我的Testing类的main方法中,我试图像这样创建一个ZipIterator对象

int[] arr1 = {1,5,3,1,6};
double[] arr2 = {2.3,42.1,1.6,6.43};
ZipIterator<int[],double[]> zip =  new ZipIterator<int[],double[]>(arr1,arr2);

但我不断收到错误:

error: incompatible types: int[] cannot be converted to int[][]

我不确定自己在做什么错。 如果有人可以帮助,将不胜感激!

考虑当Kint[]Vdouble[]ZipIterator<K[], V[]>的签名。

您需要实例化的是ZipIterator<Integer, Double> ; 您不能参数化具有原始类型的类。

是的,由于装箱/拆箱,效率低下。 如果需要更高的性能,请使包装器类将原始类型的数组保留为实例变量。 不过,要使其具有良好的参数化将非常棘手。

仔细看看会发生什么:

您将int[]用作通用类型K

ZipIterator<int[], double[]> zip = new ZipIterator<int[],double[]>(arr1, arr2);

但是,您的构造函数正在接受K数组,因此int[]数组将需要int[][]

public ZipIterator(K[] arr1, V[] arr2) { ... }

笔记:

  • 您不应将数组与泛型一起使用,而应使用List接口:

     public ZipIterator(List<K> arr1, List<V> arr2) { ... } 

    或者,就像提到的4castle一样,您甚至可以使用Iterable接口。

  • 与其他人所说的不同,即使它是原始类型的数组,数组也始终是对象。 因此,对K使用int[]是完全有效的,而对int则无效。

应该是ZipIterator<int,double> zip = new ZipIterator<int,double>(arr1,arr2);

使用包装器类

Integer[] arr1 = {1,5,3,1,6};
Double[] arr2 = {2.3,42.1,1.6,6.43};
ZipIterator<Integer,Double> zip =  new ZipIterator<>(arr1,arr2);

根据@ 4castle的评论编辑了我的答案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM