gpt4 book ai didi

java - 在java中创建一个通用数组

转载 作者:行者123 更新时间:2023-12-02 17:45:09 25 4
gpt4 key购买 nike

我正在尝试在 java 中创建一个通用数组 - 其中我遇到了一些问题 - 如何创建一个大小为 6 且内部大小为 byte[] 和一个 Integer 的元组数组?

谢谢

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;
}
}

最佳答案

你可以使用原始类型:

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。

关于java - 在java中创建一个通用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23141696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com