1

我有一个 ArrayList 的套接字。如何从列表中删除变量中的同一个套接字。例如:

sockets = new ArrayList<Socket>();
sockets.add(socket);
sockets.add(socket1);
sockets.add(socket2);

现在我想删除它的索引socket1,未知。

4

3 回答 3

3

假设您有对Socket要删除的对象的引用,那么只需调用remove您的ArrayList

sockets.remove(socket1);

这是可行的,因为即使Socket没有实现该equals方法,也使用了 Object 类的引用相等性。只要该Socket对象在ArrayList,remove就会删除它。

于 2013-03-06T20:34:18.817 回答
1

这段代码:

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class RemoveSocketFromAList {
   public static void main( String[] args ) throws IOException {
      List< Socket > sockets = new ArrayList<>( 3 );
      Socket google = new Socket( "www.google.com", 80 );
      Socket bing   = new Socket( "www.bing.com"  , 80 );
      Socket yahoo  = new Socket( "www.yahoo.com" , 80 );
      sockets.add( google );
      sockets.add( bing   );
      sockets.add( yahoo  );
      System.out.println( sockets.size());
      sockets.remove( bing );
      System.out.println( sockets.size());
      System.out.println( sockets );
   }
}

输出:

3
2
[Socket[addr=www.google.com/74.125.230.243,port=80,localport=62411], Socket[addr=www.yahoo.com/87.248.122.122,port=80,localport=62413]]

List.remove()是有效的。

于 2013-03-06T21:14:50.543 回答
-1

虽然你没有完全提供你的代码,但在这里我给你一个例子,如何从下面的数组列表中删除一个项目..

// create an empty array list with an initial capacity
    ArrayList<String> arrlist = new ArrayList<String>(5);

    // use add() method to add values in the list
    arrlist.add("A");
    arrlist.add("B");
    arrlist.add("C");
    arrlist.add("D");
    arrlist.add("E");

    System.out.println("Size of list: " + arrlist.size());

    // let us print all the values available in list
    for (String value : arrlist) {
      System.out.println("Value = " + value);
    }  

    // Removes first occurrence of "C"
    arrlist.remove("C");

    System.out.println("Now, Size of list: " + arrlist.size());

    // let us print all the values available in list
    for (String value : arrlist) {
      System.out.println("Value = " + value);
    }  

//另一个例子

ArrayList<String> arlist=new ArrayList<String>();

//<E> it is return type of ArrayList

arlist.add("First Element"); // adding element in ArrayList
arlist.add("Second Element");
arlist.add("Third Element");
arlist.add("forth Element");
arlist.add("fifth Element");

// remove array list element by index number
arlist.remove(3);

// remove ArrayList element by Object value
arlist.remove("fifth Element");

// get elements of ArrayList 
for(int i=0;i<arlist.size();i++)
{
    System.out.println("ArrayList Element "+i+" :"+arlist.get(i));
}
于 2013-03-06T20:31:31.363 回答