[英]iterating through list in java using for loop
如何使用索引迭代列表數據結構。 例如,考慮一個列表形式的句子,每個元素都是一個單詞。 我可以使用索引單步執行每個單詞嗎? 像這樣的東西 -
// sentence defined something like this - List<String>
int size = sentence.size();
for (int i=0; i<size-1; i++)
{
System.out.println(sentence[i] + " " + sentence[i+1]);
}
當然上面的代碼不起作用,但是可以在這些行上做點什么嗎? 正如您所看到的,我想訪問兩個連續的元素並使用迭代器,它開始變得非常混亂。
您可以使用get(i)
方法而不是[i]
:
for (int i=0; i<size-1; i++) {
System.out.println(sentence.get(i) + " " + sentence.get(i+1));
}
List
實例與數組不同。 他們有特定的方法來獲取某些索引的項目。 嘗試這個:
// sentence defined something like this - List<String>
int size = sentence.size();
for (int i=0; i<size-1; i++)
{
System.out.println(sentence.get(i) + " " + sentence.get(i + 1));
}
現在如果你有一個數組(例如String[] sentence = new String[]{"hello", "there"}
),你所擁有的就可以了。
作為一個側面說明,Java有既能陣列和上使用for-each循環List
S:
for (String s : sentence) {
// do something
}
當然,這不能在你的情況下使用,因為你在循環的每次迭代中訪問多個索引處的元素 - 但重要的是要知道存在這樣的東西。
Java中的x[i]
表達式語法只能用於數組。 沒有其他的。
正如其他答案所述,使用索引逐步瀏覽Java列表元素的方法是使用List.get(int)
。 但是,執行此操作時需要考慮一個重要的性能問題。
問題是get(int)
調用的成本取決於您使用的List
實現類:
對於ArrayList
(或Vector
),長度為N的列表上的get(int)
操作為O(1)
。 這意味着它不依賴於列表長度,實際上它很便宜:只比someArray[i]
貴一點。
對於LinkedList
,列表上的get(int)
操作必須從頭開始逐步執行列表,直到它到達您要求的位置。 如果列表長度為N,那么get(int)
的平均成本(假設列表中的隨機位置)是O(N)
; 即它與列表長度成比例。 如果長度很長,那將是昂貴的。
相比之下,如果您使用Iterator
(顯式地或通過使用for (E e : l)
語法隱式),則獲取java.util
和java.util.concurrent
所有列表實現的每個元素將為O(1)
java.util.concurrent
(忽略多線程問題,如重度爭用)。
話雖如此,有些情況下迭代器不起作用,應用程序需要使用索引。
在這種情況下,你也可以使用Iterator:
首先將ur元素放在arraylist上並嘗試使用Iterator,如下所示:
ArrayList arrayList = new ArrayList();
Iterator itr = arrayList.iterator();
while(itr.hasNext())
{
System.out.println(itr.next()); // Print out the elements from arraylist
}
您可以在不使用索引的情況下處理列表中的連續值對。 這是一種方式:
private void processWordsInSentence(List<String> sentence) {
Iterator<String> it = sentence.iterator();
if (it.hasNext()) {
String previous = it.next();
while(it.hasNext()) {
String current = it.next();
// use previous and current values, e.g.
System.out.println(previous + " " + current);
previous = current;
}
}
}
你為什么要使用這樣的東西而不是sentence.get(index)
? 我會提出幾個原因:
在您的示例中,您的處理實際上是關注列表中的連續值,而不是它們的位置。 因此,不必明確地擺弄索引就沒有“增值”。
請記住, List<T>
是具有多個實現的接口。 ArrayList<T>
在常量時間內執行.get(index)
,但在LinkedList<T>
上的相同調用需要與index
的值成比例的時間。 因此可能存在真正的性能考慮因素。
上面的processWordsInSentence
實現必須明確處理少於兩個元素的列表的情況。 保護中的循環if
可以用for
語句編寫,如果你喜歡那種風格,可以將遍歷與處理實際數據分開一些。
private void processWordsInSentence(List<String> sentence) {
Iterator<String> it = sentence.iterator();
if (it.hasNext()) {
for (
String previous = it.next(), current = null;
it.hasNext();
previous = current
) {
// use previous and current values, e.g.
System.out.println(previous + " " + current);
}
}
}
試試這個簡單的代碼:
List mobileSoftwares = new ArrayList();
mobileSoftwares.add("Android");
mobileSoftwares.add("IOS");
mobileSoftwares.add("Blackberry");
int size = mobileSoftwares.size();
for (int i = 0; i < size - 1; i++)
{
System.out.println(mobileSoftwares.get(i));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.