为什么我的arraylist不会添加多个对象?

时间:2016-03-03 02:00:40

标签: java arraylist

如果你看看我的if else块,你会看到我试图将一个人对象添加到我的arraylist中。但是,它只会向arraylist添加/保留一个对象。如果我循环遍历数组并打印出所有元素,那么只有一个人对象,并且它始终是实例化的最后一个人。有谁知道为什么会这样?我已经在Stack Overflow上查看了类似帖子,并且找不到任何帮助。

public class ClientThread extends Thread {

  static ArrayList<Person> array = new ArrayList<Person>();

  Socket socket;

  public ClientThread(Socket socket) {
    this.socket = socket;
  }

  public void run() {
    try {
      handleConnection(socket);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  public void handleConnection(Socket server) throws IOException {
    String x = "";
    //to get input from the client
    BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
    //Out to the client -- Enable auto-flush
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
    //prints "got a connection from X" on server terminal
    System.out.println("got connection from " + server.getInetAddress().getHostName() + "\n");

    while (true) {
      // get input from the client
      if((x = in.readLine()).length() != 0) {
        if (x.equals("END")) {
          System.out.println("This thread is shutting down. BYE!");
          break;
        } else if (x.equals("STORE") || x.equals("store")) {
          String storeName;
          System.out.println("Client wants to store someone's number.");
          out.println( "SERVER > Enter a name and number: ");
          storeName = in.readLine();
          array.add(new Person(storeName));
        } else {
          System.out.println("Echoing: " + x);
          out.println( "SERVER > ");
        }
      }
    }             
  }    
}

这是我的类Person

的代码
class Person {

  protected String name;

  public Person(String name) {
        this.name = name;       
  }

  //overide toString
  public String toString() {
    return name;
  }
}

0 个答案:

没有答案
相关问题