简体   繁体   中英

Java: Creating a class recognized somewhere else in the file

In ClassA.java I have

class User {
    private int id;
    private String nick;
    public int getId() {
        return id;
    }
    public void setId(int i) {
        id = i;
    }
    public String getNick() {
        return nick;
    }
    public void setNick(String n) {
        nick = n;
    }
}

public final class ClassA {
    private List<User> = new LinkedList();
    public Collection<String> getUsers() {
        LinkedList out = new LinkedList();
        Iterator loop = out.iterator();
        while (loop.hasNext()) {
            User u = loop.next();
            out.add(u.getNick());
        }
        return out;
    }
}

When I compile this, I get an error telling me that on the line containing

User u = loop.next();

It tells me that u cannot be cast to a User . Is there something further I should do to indicate to the compiler the static type of u ?

LinkedList (or List in general) is a generic type. Without specifying the generic argument, by default it would be interpreted as being an Object . You need to specify your list accordingly:

List<User> out = new LinkedList<>();

You need to use generics:

List<User> out = new LinkedList<>();
Iterator<User> loop = out.iterator();

I think you should add a constructor to the class User

User(){}

and here

private List<User> test = new LinkedList();

a name

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