ArrayBased Lists Suppose we create the following ArrayList i
Array-Based Lists
Suppose we create the following ArrayList instance:
ArrayList <String> words = new ArrayList<String>();
And then we insert several words into words. Write the code to print out each element of words that has exactly four letters. You should have three different version of the code:
-using an index;
-using an explicit iterator;
-using an enhanced for loop
Thanks!
Solution
Note:Could You please check the code and the output.If any modifications required I will modify it.Thank You.
ArrayListDemo.java
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo {
public static void main(String[] args) {
//Declaring variable
int i=0;
//Creating an ArrayList which holds Strings
ArrayList <String> words = new ArrayList<String>();
//Adding Words to the ArrayList
words.add(\"Hello\");
words.add(\"Mary\");
words.add(\"John\");
words.add(\"Thomson\");
words.add(\"Kristen\");
words.add(\"Pointing\");
words.add(\"Ken\");
words.add(\"Gary\");
//Displaying the Elements In the ArrayList based on the no of characters in each word
System.out.println(\"List of elements in the ArrayList whose size is equal to 4 Using an Index :\");
//1.Displaying Elements which contains Exactly 4 letters Using An Index
while(words.size()>i)
{
words.get(i);
if(words.get(i).length()==4)
System.out.println(words.get(i));
i++;
}
System.out.println(\"List of elements in the ArrayList whose size is equal to 4 using an Explicit Iterator :\");
//2.Displaying Elements which contains Exactly 4 letters Using An Explicit Iterator
String str;
Iterator<String> itr=words.iterator();
while(itr.hasNext())
{
str=itr.next();
if(str.length()==4)
System.out.println(str);
}
//3.Displaying Elements which contains Exactly 4 letters Using an enhanced for loop
System.out.println(\"List of elements in the ArrayList whose size is equal to 4 using an enhanced for loop :\");
for(String s:words)
{
if(s.length()==4)
System.out.println(s);
}
}
}
___________________________
Output:
List of elements in the ArrayList whose size is equal to 4 Using an Index :
Mary
John
Gary
List of elements in the ArrayList whose size is equal to 4 using an Explicit Iterator :
Mary
John
Gary
List of elements in the ArrayList whose size is equal to 4 using an enhanced for loop :
Mary
John
Gary
_____________Thank You

