Can we iterate through collection using for loop?
Answers were Sorted based on User's Feedback
Answer / qim2010
Yes.
/*
Iterate through a Collection using Java Iterator Example
This Java Example shows how to iterate through a Collection
using Java Iterator.
*/
import java.util.Iterator;
import java.util.ArrayList;
public class JavaIteratorExample {
public static void main(String[] args) {
//create an ArrayList object
ArrayList aList = new ArrayList();
//populate ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
/*
Get Iterator object by invoking iterator method of
collection.
Iterator provides hasNext() method which returns
true if has more
elements. next() method returns the element in
iteration.
*/
//iterate through the ArrayList values using
Iterator's hasNext and next methods
for (Iterator itr = aList.iterator(); itr.hasNext();) {
//while(itr.hasNext())
System.out.println(itr.next());
/*
Please note that next method may throw a
java.util.NoSuchElementException
if iteration has no more elements.
*/
}
}
}
Is This Answer Correct ? | 3 Yes | 0 No |
Answer / haneef
Yes, We can
Set set=new HashSet();
set.add("one");
set.add("two");
for(Iterator it=set.iterator();it.hasNext();)
{
System.out.println(it.next());
}
Is This Answer Correct ? | 3 Yes | 1 No |
What are the similarities between an array and an ArrayList?
Difference between canvas class & graphics class?
If you do not want your class to be inherited by any other class. What would you do?
What are locale settings?
What is runtime polymorphism or dynamic method dispatch?
interface X{ void m1(); void m2(); } class Child2 extends Object implements X { public void m1(){ System.out.println("Child2 M1"); } public void m2(){ System.out.println("Child2 M2"); } } public class ParentChildInfterfaceDemo { public static void main(String[] args){ X x = new Child2(); X x1 = new Child2(); x.m1(); x.m2(); x.equals(x1); } } Will the above code work? If yes? Can you please explain why the code x.equals(x1) will work as the equals method is called on interface reference vaiable?
Is node a data type in java?
Is set thread safe java?
What is difference between hash mapping and hash table?
What is this keyword used for?
what is tempplate pattern
Which access specifier can be used with class ?