【问题标题】:Create a generic array in java [duplicate]在java中创建一个通用数组[重复]
【发布时间】:2014-04-17 19:21:49
【问题描述】:

我正在尝试在 java 中创建一个通用数组 - 我遇到了一些问题 - 我怎样才能创建一个大小为 6 且内部有一个字节 [] 和一个整数的元组数组?

谢谢

private Tuple<byte[], Integer>[] alternativeImages1 = new Tuple<byte[], Integer>[6];

class Tuple<F, S> {

    public final F first;
    public final S second;

    public Tuple(final F first, final S second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        final Tuple tuple = (Tuple) o;
        return this.first == tuple.first && this.second == tuple.second;
    }

    @Override
    public int hashCode() {
        int result = this.first != null ? first.hashCode() : 0;
        result = 31 * result + (this.second != null ? second.hashCode() : 0);
        return result;
    }
}

【问题讨论】:

  • 您不能创建带有类型参数的类型数组;这是Java中数组的限制。这个问题之前有人问过,例如:Array of Generic List

标签: java arrays generics


【解决方案1】:

你可以使用原始类型:

Tuple[] array = new Tuple[6];

或者您可以进行未经检查的转换:

Tuple<byte[], Integer>[] array = (Tuple<byte[], Integer>[])new Tuple[6];

// or just this because raw types let you do it
Tuple<byte[], Integer>[] array = new Tuple[6];

或者您可以使用列表来代替:

List<Tuple<byte[], Integer>> list = new ArrayList<Tuple<byte[], Integer>>();

我建议改用列表。

在前两个选项之间进行选择,我会推荐未经检查的转换,因为它会为您提供编译时检查。但是,如果您将其他类型的元组放入其中,它不会抛出 ArrayStoreException。

【讨论】:

  • 如果您可以使用固定大小的列表而不需要进行边界检查,那么我会使用我认为的列表(特别是如果我可以删除默认的空值)
  • 确实,List 与数组有一些不同的功能。虽然可以扩展 ArrayList 并使其表现得更像一个数组。如果你愿意,我可以给你一个例子,不过我建议你习惯使用 List 的功能。它通常更优越,除了低级处理(如 I/O)或固定长度很重要的数据结构(如哈希表)外,几乎没有理由使用数组。
猜你喜欢
  • 2012-03-28
  • 1970-01-01
  • 2012-05-27
  • 2011-03-09
  • 2017-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多