简体   繁体   中英

ArrayList Java accessing element data variables

So I am trying to access the data members of an element in my ArrayList, but eclipse shows that the data member is not a field.

System.out.println(users.get(i).name);

users is an arrayList and the language is Java.

Thanks!

PS.

This is the definition of User

public class User {
    public String name;
    public String password;
}

I declare users like this:

ArrayList users;
users=new ArrayList<User>(NOOFUSERS);

Fixed the error!! Thank you!

Is your ArrayList declared this way?

ArrayList users = ...

If thats the case this will fix your Problem.

ArrayList<User> users = ...

This

ArrayList users; 
users=new ArrayList(NOOFUSERS);

is a Raw Type and it isn't programming to the List interface (described in the Oracle Java tutorial here ). I would instead use the interface and something like,

List<User> users = new ArrayList<>(); // <-- diamond operator Java 7 and above,
                                      //     use <User> for 5 and 6.

When Eclipse says that "name is not a field", it means that the attribute name is not an attribute of "some class". The term "some class" is generic because you are not reporting the line of code where you declare the ArrayList. Since ArrayList is generic, you may specify its parameter, ie the type of objects the ArrayList contains. If you don't, then the compiler (and then Eclipse) assumes it contains instances of Objects. So, you may be declaring

ArrayList users = new ArrayList(); // ArrayList of Objects, which do not have any field called "name"

If you specify the parameter User this way:

ArrayList<User> users = new ArrayList<User>(); // ArrayList of Users

You will fix the compile error. Also, this way you will remove the warning that you are probably getting on the ArrayList definition ("users is a raw type").

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