3

How does one iterate through a list datastructure using indices. For example consider a sentence in form a list with each element being a word. Can I step through each word using the index? Something like this --

// 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]);
}

ofcourse the above code doesn't work but is it possible to do something on those lines? As you can see, I want to access the two consecutive elements and using iterators, it starts becoming really messy.

6 Answers 6

6

You can use the get(i) method instead of [i]:

for (int i=0; i<size-1; i++) {
    System.out.println(sentence.get(i) + " " + sentence.get(i+1));
}
5

List instances are not the same as arrays. They have specific methods for obtaining items at certain indexes. Try this:

// 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));
}

Now if you had an array (e.g. String[] sentence = new String[]{"hello", "there"}), what you had would work fine.

As a side note, Java has a for-each loop that can be used on both arrays and Lists:

for (String s : sentence) {
    // do something
}

Of course, this can't be used in your case because you're accessing elements at multiple indexes in each iteration of your loop - but it's important to know that something like this exists.

2

The x[i] expression syntax in Java can only be used for arrays. Nothing else.

As other answers have stated, the way to step through the elements of a Java list using indices is to use List.get(int). However, there is an important performance issue that needs to be considered when you do this.

The issue is that the cost of a get(int) call depends on what List implementation class you use:

  • For an ArrayList (or a Vector) the get(int) operation on a list of length N is O(1). That means that it does not depend on the list length, and in fact it is cheap: only a bit more expensive than an someArray[i].

  • For a LinkedList, the get(int) operation on a list has to step through the list from the beginning until it reaches the position you asked for. If the list length is N, then the average cost of get(int) (assuming a random position in the list) is O(N); i.e. it is proportional to the list length. If the length is long, then that will be expensive.

By contrast, if you use an Iterator (explicitly, or implicitly by using the for (E e : l) syntax), getting each element will be O(1) for all of the list implementations in java.util and java.util.concurrent (ignoring multi-threading issues such as heavy contention).

Having said that, there are some cases where iterators don't work, and the application needs to use indices.

0

You can also use Iterator in this case for ex:

first of all put ur elements on arraylist and try to use Iterator like this:

ArrayList arrayList = new ArrayList();

Iterator itr = arrayList.iterator();

while(itr.hasNext())
{
  System.out.println(itr.next()); // Print out the elements from arraylist

}
0

You can process consecutive pairs of values from a list without using indices. Here's one way:

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;
        }
    }
}

Why would you want to use something like this instead of sentence.get(index)? I would offer a couple of reasons:

  1. In your sample, your processing is really concerned with consecutive values from the list, not their positions. So there's no "value add" to having to fiddle with the index explicitly.

  2. Remember that List<T> is an interface with multiple implementations. ArrayList<T> performs .get(index) in constant time, but that same call on a LinkedList<T> requires time proportional to the value of index. So there could be a real performance consideration.

The processWordsInSentence implementation above does have to deal explicitly with the case of lists with less than two elements. The loop inside the guarding if can be written with a for statement, to separate traversal from processing the actual data a bit more aggressively, if you prefer that style.

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

Try this simple code :

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));
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.