找到兼容的插座

时间:2013-03-06 20:19:14

标签: java sockets

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

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

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

3 个答案:

答案 0 :(得分:3)

假设您引用了要删除的Socket对象,请在ArrayList上致电remove

sockets.remove(socket1);

这很有效,因为即使Socket没有实现equals方法,也会使用Object类的引用相等性。只要该Socket对象位于ArrayList中,remove就会将其删除。

答案 1 :(得分: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()有效。

答案 2 :(得分:-1)

虽然你没有完全提供你的代码,但在这里我举例说明如何从下面的arraylist中删除一个项目..

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