Getting an specific argument from an list object in Java

Don't know if I formulated the question the right way, but here goes... I need to print the usernames of the objects from the list users. Here is the User class:

public class User {
   public String username;
   public String email;
   public String membership;

   public User (String us, String em, String mm){
       us=username;
       em=email;
       mm=membership;
}}

And here is the main class:

public class Main {
    List<User> users = new ArrayList<User>();

    users.add(new User("johnsmith", "johnsmith@gmail.com", "Premium"));
    users.add(new User("walterwhite", "walter.white@gmail.com", "Beginner"));
    users.add(new User("drwho", "doctorwho@gmail.com", "Gold"));
    users.add(new User("parker", "parker2@gmail.com", "Premium"));

    for (int i=0; i<users.size(); i++){
        System.out.println(); // <--------- So I don't know what to use here
}}}

What do I use in the println() method? I need to print ONLY the usernames (johnsmith, walterwhite, drwho, parker). Or any other object (email or whatever, I just need to know how to print certain arguments from a list). Already tried println(users.membership), println(membership) and similar variations...

Jon Skeet
people
quotationmark

I suspect you want something like:

for (int i = 0; i < users.size(); i++) {
    // Access the user by position in the list
    User user = users.get(i);
    // Now print the username for that specific user
    System.out.println(user.username);
}

I've separated the loop body into two statements for clarity, but it's equivalent to:

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

This is using the List.get(int) method to access the item at a particular index in the list.

Now, there are better ways of doing this:

  • As noted in comments, the assignments in your constructor are backwards. You need to assign to the fields from the parameters.
  • Your fields should generally be private. Add public "getter" methods where necessary.
  • Use the enhanced-for-loop to simply access each element of a collection in sequence:

    for (User user : users) {
        System.out.println(user.getUserName()); // After addressing the above
    }
    

people

See more on this question at Stackoverflow