2012-03-11 84 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等於列表的第一個元素。

相關問題