Reputation: 32331
I have taken this example from net . But when i tried it is not compiling saying cannot convert Object to String
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList names = new ArrayList();
names.add("Amy");
names.add("Bob");
names.add("Chris");
names.add("Deb");
names.add("Elaine");
names.add("Frank");
names.add("Gail");
names.add("Hal");
for (String nm : names)
System.out.println((String)nm);
}
}
If it is a normal for loop i could have done list.get(element index).toString() . but how to do in enhanced for loop ??
Upvotes: 1
Views: 4315
Reputation: 12633
You have not used Generics so you cannot safely do:
for (String nm : names)
As your ArrayList holds Objects, of which String IS A Object. You must surely be using Java 5 or above, so use Generics to say your List will only contain Strings:
List<String> names = new ArrayList<String>();
If you didn't use Generics you would need to do:
for (Object nm : names)
System.out.println(nm);
Passing the Object to the println method will call its toString method anyhow.
But use Generics!
Upvotes: 1
Reputation: 1500893
You shouldn't bypass type safety by calling toString()
- you should use generics to start with:
List<String> names = new ArrayList<String>();
Now your for
loop will compile (you can get rid of the cast in the System.out.println
call btw) and the compiler will prevent you from adding a non-string to your list.
See the Java generics tutorial for a starting point on generics, and the Java Generics FAQ for more information that you'll ever want to know :)
Upvotes: 6