1

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 ??

Pawan
  • 31,545
  • 102
  • 256
  • 434

2 Answers2

6

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 :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Great answer , i didn't thought that there would be a relation for Enhanced for loop and Generics . Thanks a lot . – Pawan Mar 30 '12 at 06:47
  • I have one more question why people use List names = new ArrayList(); , rather than ArrayList names = new ArrayList(); ? – Pawan Mar 30 '12 at 06:48
  • @yyyi777 See [What does it mean to "program to an interface"?](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Jesper Mar 30 '12 at 06:50
  • @yyyi777: It's *generally* a good idea to code to the interface rather than the concrete type, as it shows that you're only *thinking* about it as "a list", and not using any `ArrayList`-specific members. – Jon Skeet Mar 30 '12 at 06:50
  • @yyyi777 List names = new ArrayList() is commented in http://cyclo.ps/books/Prentice.Hall.Effective.Java.2nd.Edition.May.2008.pdf – cl-r Mar 30 '12 at 11:40
1

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!

planetjones
  • 12,469
  • 5
  • 50
  • 51