创建一个原始int列表? [英] Create a List of primitive int?

查看:328
本文介绍了创建一个原始int列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法创建一个基本的int或任何图元在java中的列表,如下?

Is there a way to create a list of primitive int or any primitives in java like following?

List<int> myList = new ArrayList<int>();

看来我可以做 List myList = new ArrayList code>

It seems I can do List myList = new ArrayList();

并将int添加到此列表中。但这就意味着我可以在这个列表中添加任何内容。

and add "int" into this list. But then this would mean I can add anything into this list.

是我唯一的选择,创建一个int数组并将其转换为列表或创建一个Integer对象列表?

Is my only option, creating an array of int and converting it into a list or creating a list of Integer objects?

推荐答案

在Java中泛型类型参数必须是对象。由于基本元素不扩展 Object ,它们不能用作参数化类型的泛型类型参数。

In Java generic type arguments must be objects. Since primitives do not extend Object they cannot be used as generic type arguments for a parametrized type.

整数 int 的包装器的类:

List<Integer> list = new ArrayList<Integer>();

如果使用Java 7,您可以使用diamond操作符简化此声明:

If your using Java 7 you can simplify this declaration using the diamond operator:

List<Integer> list = new ArrayList<>();

对于Java中的自动装箱,原始类型 int 将在必要时变为整数

With autoboxing in Java the primitive type int will become an Integer when necessary.


自动转换是Java编译器在原始类型和对应的对象包装之间进行
的自动转换
类。

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

因此,以下内容有效:

int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);

System.out.println(list.get(0)); //prints 1

这篇关于创建一个原始int列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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