如何设置一个等于整数ArrayList中第一个元素的变量?

时间:2012-03-11 07:14:19

标签: java

这是我现在的代码。我试图使变量n等于整数数组List中的第一个元素。我尝试使用set方法,但这只适用于String arrayLists。

ArrayList<Integer> intList = new ArrayList<Integer>();
int x = 5;// just put in after Q19.
??int n = myList;
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(x);

3 个答案:

答案 0 :(得分:3)

ArrayList<Integer>中的第一个条目可通过get(0)作为Integer访问。然后,要从int获取Integer,您可以使用intValue(尽管当您使用Java5或更高版本时,您不需要;编译器会自动将其取消装箱你):

所以:

int n = intList.get(0).intValue(); // If you want to be explicit
int n = intList.get(0);            // If you want to use auto-unboxing

请注意,该列表可能包含null个值,因此可能会采取一些防御措施:

int n;
Integer i = intList.get(0);
if (i != null) {
    n = i;                         // Using auto-unboxing
}
else {
    // Do whatever is appropriate with `n`
}

这个问题还不清楚。如果您希望两者之间存在某种持久的联系,则不能(n不是int)。但由于Integer是不可变的,我没有看到你想要的任何理由,因为两者之间持久链接的唯一真正原因是你可以使用引用和不可变的方式看到状态更改对象没有状态变化。

答案 1 :(得分:0)

我想你想在你的集合中有重复的元素,你不能在Set中有重复的元素,就像在数学中定义set一样。 Oracle的Java代表Set集合:

A collection that contains no duplicate elements. 
More formally, sets contain no pair of elements e1 and e2 
such that e1.equals(e2), 
and at most one null element. As implied by its name, 
this interface models the mathematical set abstraction.

但是这个限制在List集合中不存在,Oracle的Java称为'List'集合:

Unlike sets, lists typically allow duplicate elements. 
More formally, lists typically allow pairs of elements e1 and e2 
such that e1.equals(e2), and they typically allow multiple null elements 
if they allow null elements at all. 
It is not inconceivable that someone might wish to implement 
a list that prohibits duplicates, 
by throwing runtime exceptions when the user attempts to insert them, 
but we expect this usage to be rare.

所以你的set实例中不能有重复的elemet。

有关详细信息,请参阅本网站中的以下问题:

  

块引用

答案 2 :(得分:0)

看起来真的像家庭作业:-D

int n = intList.get(0)

我认为你不需要IntValue()部分,因为你已经在处理整数。

.get(0)

是列表的第一个元素。

.get(1)

将是第二个,依此类推。

当然,您应首先将元素添加到列表中,然后尝试使n等于列表的第一个元素。