我如何重写这个类,以便它维护Arraylist中的用户而不是java中提供的数组?

时间:2014-04-11 15:23:41

标签: java arraylist

这是邮箱整体系统的一部分,因此不应该对类的接口方法进行任何更改,因为我将不得不更改整个系统。

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++;
    }
  }
}

2 个答案:

答案 0 :(得分:1)

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); 
    }
  }
}

要了解ArrayList thisthis,当然还有this

注意:(更高级的选项)
您可以覆盖equals()类中的User方法,并完全省略findUser方法;

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;
    }
}

而是检查用户是否存在

if (users.contains(u))
      System.out.println("User already exists");

答案 1 :(得分:0)

使用User[] users而不是使用ArrayList<type>,即数组。在这里阅读更多信息---&gt; http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html和 这里---&gt; http://www.dummies.com/how-to/content/use-array-lists-in-java.html