开发者

How to print the output of an accessor of every instance of a class?

How would you go about creating a class like this:

public class tmUser {
    
    private String Username;
    private int wHours;
    static int numUsers;
    
    
    public tmUser(){
        Username = "";
        wHours = 0;
    }
    
    public tmUser(String U, int H){
        Username = U;
        wHours = H;
    }
    
    public void setUsername(String U){
        Username = U;
    }
    
    public void setwHours(int H){
        wHours = H;
    }
    
    public String getUsername(){
        return Username;
    }
    
    public int getwHours(){
     开发者_C百科   return wHours;
    }
    
    public static void initnumUsers(){
        numUsers = 0;
    }
    
    public static int getnumUsers(){
        return numUsers;
    }
}

and then printing all of tmUser instances Username variable? in maybe a for each loop? I'm hoping for something like:

for each(tmUser){
    System.out.println(Username);
}

This is for a menu in a program which displays all created users usernames.


You almost had it:

List<TmUser> tmUsers = ... 
for(TmUser user : tmUsers) {
    System.out.println(user.getUsername());
}

You would also want to capitalize tmUser into TmUser.


When you create a tmUser add it to a collection like

List<TmUser> tmUsers = new ArrayList<TmUser>();

TmUser tmUser = new TmUser(username, hoursWorked);
tmUser.add(tmUser);

// later
for(TmUser tmUser: tumUsers) 
  System.out.println(tmUser.getUsername());


You need to store all of tmUser instances somewhere first. You could do it this way:

public class tmUser {
...
public static List<tmUser> USERS = new ArrayList<tmUser>();

public tmUser() {
   ...
   USERS.add( this );
}

and then printing:

for (tmUser user : tmUser.USERS) {
    System.out.println(user.getUsername());
}


The 3 current answers are basically the same. Just wanted to add that if the class defined a toString() that returned the user name, it would not be necessary to add the .getUsername() method call, since System.out.println(Object) will automatically call the toString() method.

Whether this could work for your use case is debatable. The toString() method would normally provide more data on the object.


As the answers already posted indicate, this would involve maintaining some sort of data structure that holds references to all instances of tmUser (e.g. a List<tmUser>).

This would mean that a reference to each and every instance ever created will always be held there, they will never be garbage collected. You could explicitly remove them when you decide an instance is no longer needed, but then you would have to keep track of the life cycle of all instances, and basically end up doing memory management yourself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜