问题描述:

This is part of an overall system of a mailbox so there shouldn't be any change in the interface methods of the class since I will then have to change the overall system.

public class Userlist

{

private User[] users;

private int maxUser;

private int numberUsr;

public Userlist()

{

maxUser = 2;

users = new User[maxUser];

numberUsr = 0;

}

public User findUser(String username)

{

for (int i = 0; i < numberUsr; i++)

{

if (users[i].userName.equals(username))

return users[i];

}

return null;

}

public void addUser(User u)

{

if (findUser(u.userName) != null)

System.out.println("User already exists");

else

{

if (numberUsr == maxUser)

{

maxUser = 2 * maxUser; // double the size of the array

User[] usersTmp = new User[maxUser];

System.arraycopy(users, 0, usersTmp, 0, numberUsr);

users = usersTmp;

}

users[numberUsr] = u;

numberUsr++;

}

}

}

网友答案:
import java.util.ArrayList;

public class Userlist
{

  private ArrayList<User> users; 

  public Userlist()
  {
    users = new ArrayList<User>();
  }

  public User findUser(String username)
  {
    for (User i : users)
    {
      if (i.userName.equals(username))
        return i;
    }
    return null;
  }

  public void addUser(User u)
  {
    if (findUser(u.userName) != null)
      System.out.println("User already exists");
    else
    {
     users.add(u); 
    }
  }
}

To learn about ArrayList look at this, this and of course this.

Note: (More advanced options)
You can override the equals() method in the User class and omit the findUser method completely;

class User {
    String userName;
    /*
     * 
     * Do whatever 
     * 
     */

    @Override
    public boolean equals(Object object)
    {
        boolean theSame = false;

        if (object != null && object instanceof User)
        {
            theSame = this.userName.equals(((User) object).userName);
        }

        return theSame;
    }
}

instead check for existence of a user with

if (users.contains(u))
      System.out.println("User already exists");
网友答案:

Instead of using User[] users, which is the array, use ArrayList<type>. Read about it more here ---> http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html and here ---> http://www.dummies.com/how-to/content/use-array-lists-in-java.html

相关阅读:
Top