简体   繁体   中英

Why is this Java code not compiling?

Here is my code:

public class MessagePrettier<T> {

    private final T uglyMessage;

    public MessagePrettier(T uglyMessage) {
        this.uglyMessage = uglyMessage;
    }

    public List<String> stringList() {
        List<String> strings = new ArrayList<String>();
        strings.add("Pretty version of: " + uglyMessage.toString());
        return strings;
    }

    public static void main(String[] args) {
        MessagePrettier<Integer> p = new MessagePrettier<Integer>(new Integer("25"));
        List list = p.stringList();
        for (String s : list) {
            System.out.println(s);
        }
    }

}

When I compile this code I will get:

java: incompatible types
  required: java.lang.String
  found:    java.lang.Object

Well stringList() returns a List of Strings, why is the compiler expecting Objects?

You are assigning your List<String> to a raw List variable :

List list = p.stringList();

Therefore, iterating over it returns Object s.

Change it to :

List<String> list = p.stringList();

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