简体   繁体   中英

java : Inside Enhanced for loop cannot Object to String

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM