在Java中创建一个通用的阵列 [英] Create a generic array in java

查看:103
本文介绍了在Java中创建一个通用的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让在Java泛型阵列 - 在我有一些问题 - 怎样才能让元组数组是大小6和大小都有一个byte []和一个整数里面呢?

感谢

 私人元组LT;字节[],整数GT; [] = alternativeImages1新的记录<字节[],整数GT; [6];一流的元组LT; F,S> {    公共决赛F第一;
    公共决赛第二;    公开元组(决赛F第一,决赛第二){
        this.first =第一;
        this.second =秒;
    }    @覆盖
    公共布尔等于(最终对象o){
        如果(这种== O)
            返回true;
        如果(O == NULL ||的getClass()!= o.getClass())
            返回false;        最后的元组元组=(数组)O;
        返回this.first == tuple.first&放大器;&安培; this.second == tuple.second;
    }    @覆盖
    公众诠释哈希code(){
        INT结果= this.first!= NULL? first.hash $ C $(℃):0;
        结果= 31 *结果+(!?this.second = NULL second.hash $ C $(℃):0);
        返回结果;
    }
}


解决方案

那么你可以使用原始类型:

 元组[]数组=新的记录[6];

或者你也可以让一个未经检查的转换:

 元组LT;字节[],整数GT; []数组=(元组LT;字节[],整数GT; [])新的元组[6];//或者仅仅是因为原始类型让你这么做
元组LT;字节[],整数GT; []数组=新的记录[6];

或者你可以使用一个列表,而不是:

 列表与LT元组LT;字节[],整数GT;>名单=新的ArrayList&LT元组LT;字节[],整数GT;>();

我推荐使用列表来代替。

前两个选项之间做出选择,我会建议选中转换,因为它会为你提供编译时检查。但是,如果你把一些其他类型的元组的它也不会抛出ArrayStoreException信息。

I am trying to make a generic array in java - in which i am having some issues - how can i make an array of Tuples which is of size 6 and has size a byte[] and a Integer inside?

Thanks

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

解决方案

Well you can use a raw type:

Tuple[] array = new Tuple[6];

Or you can make an unchecked conversion:

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

Or you can use a List instead:

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

I recommend using a List instead.

Choosing between the first two options, I would recommend the unchecked conversion because it will provide you with compile-time checks. However, it will not throw an ArrayStoreException if you put some other kind of Tuple in it.

这篇关于在Java中创建一个通用的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆