Reputation: 1
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!
Upvotes: 0
Views: 918
Reputation: 201447
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.
Upvotes: 3
Reputation: 4137
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, i.e. 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").
Upvotes: 0
Reputation: 168
Is your ArrayList declared this way?
ArrayList users = ...
If thats the case this will fix your Problem.
ArrayList<User> users = ...
Upvotes: 3