我们如何使用Java中的泛型类型和原语 [英] How can we work with generic types and primitives in Java

查看:97
本文介绍了我们如何使用Java中的泛型类型和原语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数组的对象,但是数组的类型每次都会不同.

I have an object that contains an array, but the type of the array will be diffent every time.

我可以做类似的事情

class MyObject<T>
{
    public T [] data;
}

问题是这不适用于基本类型(int,double,...),这使我可以使用Objects(Integer,Double ...).

The thing is that this does not work with primitive types (int, double, ...) and it makes me work with Objects (Integer, Double...).

有什么办法可以避免这种情况?

Is there any way of avoiding this?

非常感谢

推荐答案

您应该注意

You should be aware that autoboxing in Java may do exactly what you're looking for. See this code example from the link:

// List adapter for primitive int array
public static List<Integer> asList(final int[] a) {
    return new AbstractList<Integer>() {
        public Integer get(int i) { return a[i]; }
        // Throws NullPointerException if val == null
        public Integer set(int i, Integer val) {
            Integer oldVal = a[i];
            a[i] = val;
            return oldVal;
        }
        public int size() { return a.length; }
    };
}

get()方法正在返回普通的旧数据类型int,该数据类型将自动转换为Integer.同样,set()方法采用Integer并在数组中分配int元素.

That get() method is returning a plain old data type int that is automatically converted into an Integer. Likewise, the set() method is taking an Integer and assigning an int element in the array.

自动装箱并不是立即显而易见的功能,但可以处理自动创建对象的情况.

Autoboxing is not an immediately obvious feature but it does handle the automatic object creation.

这篇关于我们如何使用Java中的泛型类型和原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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