如何从ArrayList中

问题描述:

摆脱IndexOutOfBoundsException异常,当我开始我的服务器和客户端连接到它,我得到这个错误:如何从ArrayList中

Waiting for clients ... 
Client connected from: Driton PC 
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 

我不太明白为什么会这样,当我陆续从都遵循互联网和他的榜样工程和我的不

public class ChatServer { 

public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>(); 

public static ArrayList<String> CurrentUsers = new ArrayList<String>(); 

public static void main(String[] args) throws IOException{ 
    try 
    { 
     final int PORT = 444; 
     ServerSocket SERVER = new ServerSocket(PORT); 
     System.out.println("Waiting for clients..."); 

     while(true) 
     { 
      Socket SOCK = SERVER.accept(); 
      ConnectionArray.add(SOCK); 
      System.out.println("Client connected from: "+ SOCK.getLocalAddress().getHostName()); 
      AddUserName(SOCK); 
      Chat_Server_Return CHAT = new Chat_Server_Return(SOCK); 
      Thread x = new Thread(CHAT); 
      x.start(); 
     } 
    } 
     catch(Exception x){System.out.println(x);} 
} 

public static void AddUserName(Socket X) throws IOException 
{ 
    Scanner INPUT = new Scanner(X.getInputStream()); 
    String UserName = INPUT.nextLine(); 
    CurrentUsers.add(UserName); 
    for(int i = 1; 1 <= ChatServer.ConnectionArray.size(); i++){ 
     Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i-1); 
     PrintWriter OUT = new PrintWriter(TEMP_SOCK.getOutputStream()); 
     OUT.println("#?!"+ CurrentUsers); 
     OUT.flush(); 

    } 
} 

它运行for循环两次。

+1

'i'需要在0开始,不是1,for条件应该是'i 2013-04-05 18:18:12

+0

@SotiriosDelimanolis - 但是,在循环内部,OP使用'i-1'来索引ArrayList。 – 2013-04-05 18:22:53

+0

@SotiriosDelimanolis - 改变循环条件为'我 2013-04-05 18:27:08

轻松执行数组长度检查。

java.lang.IndexOutOfBoundsException访问集合而非数组时实际抛出。

这种异常有一种已知的ArrayIndexOutOfBoundsException这是相似的,但解决相同的目的只是使用检查集合的大小,以确保你没有脱离它的赏金。

如果什么都不删除,则for循环的条件不正确。更改为:

i <= ChatServer.ConnectionArray.size() 

但处理一个for循环是遵循基于0的索引,后来减去一个常规的方法:

for(int i = 0; i < ChatServer.ConnectionArray.size(); i++){ 
    Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i); 
+0

这并不能解释例外; OP正在调用'get(i-1)',而不是'get(i)'。循环限制似乎是正确的。 – 2013-04-05 18:20:40

+0

@Ted Hopp是的。这是一个无限循环,因为大概集合的大小永远不会低于1.最终代码运行结束,因为1(一)总是小于或等于集合大小。 – rgettman 2013-04-05 18:23:03

+0

@SotiriosDelimanolis - 明白了。我没看到这个错字。 – 2013-04-05 18:24:31