0

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!

4
  • Please post the definition of users, and what type of elements it contains. Commented Sep 21, 2014 at 21:51
  • If you want help debugging your code, you're going to have to show a bit more of it than this. Commented Sep 21, 2014 at 21:51
  • public class User { public String name; public String password; Commented Sep 21, 2014 at 21:52
  • 1
    How do you declare users? Commented Sep 21, 2014 at 21:53

3 Answers 3

3

Is your ArrayList declared this way?

ArrayList users = ...

If thats the case this will fix your Problem.

ArrayList<User> users = ...
Sign up to request clarification or add additional context in comments.

1 Comment

@rkat If this anwser is correct, you should accept. Just click the checkmark beneath the vote counter.
3

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.

Comments

0

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").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.