2012-03-11 83 views
-1

这是我现在的代码。我试图使变量n等于整数数组中的第一个元素List.I尝试使用set方法,但只适用于字符串arrayLists。如何设置一个变量等于整数ArrayList中的第一个元素?

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); 
+0

看起来像作业。是吗? – 2012-03-11 07:16:52

+0

你的意思是'int n = intList.get(0).intValue()'? – 2012-03-11 07:17:15

+2

我认出你的风格@ user1261935(又名user1254044)。伙计们,这家伙是连续的“懒惰问题”提问者。不要鼓励他。 – 2012-03-11 07:35:42

回答

3

ArrayList<Integer>的第一项是经由get(0)一个Integer访问。然后,为了获得从Integerint,您使用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` 
} 

的问题是相当不清楚。如果你想在两者之间有某种持久的联系,你不能(nint)。但由于Integer是不可变的,所以我没有看到你想要的任何理由,因为两者之间持久链接的唯一真正原因是你可以使用任何引用看到状态更改,并且不可变对象不存在状态变化。

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说的 '列表',集合:

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. 

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

更多信息,请参阅本网站的以下问题:

块引用

+0

这个问题有点含糊,但我不认为你已经回答了被问到的问题 - 我认为在问题中对set的引用与List.set()相关,而不是java.util .Set'(尽管调用'set'为_get_一个项目显然是错误的) – Tim 2012-03-11 07:25:20

+0

也许你的评论是正确的,但我猜他/她想要在集合中有重复的元素。可能是 – MJM 2012-03-11 07:27:16

+0

,但是因为他/她正在使用一个不会成为问题的'ArrayList'。 – Tim 2012-03-11 07:29:52

0

看起来真的像功课:-D

int n = intList.get(0) 

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

.get(0) 

是列表的第一个元素。

.get(1) 

将是第二等。

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

相关问题