Java,按对象获取ArrayList索引

所以我在我的代码中遇到了一个小问题:

synchronized(clients) clients.remove(this); } 

当客户端断开连接时,但现在我需要能够将该客户端的名称发送给所有其他客户端,并且为此我必须要做类似的事情

 synchronized(clients) broadcast("Remove:"+clients.get(this).name); clients.remove(this); } 

但显然我无法获得带有“this”的索引,那么我该如何获得正确的客户名称呢? 谢谢!

你为什么不简单地使用this.name? 由于您已经有了对象,为什么需要让索引再次获取对象?

编辑:

要回答标题中的问题(获取对象的索引),请使用indexOf

你看过ArrayList中的indexOf函数了吗?

 int index = clients.indexOf(this); // Do what ever... clients.remove(index); // or clients.remove(this); 

我想你想要从列表中删除特定对象。 如果从代码中获取索引

 int index = clients.get(this) 

然后你可以轻松删除

 clients.remove(index); 

或者如果从列表中获取对象,则删除

 clients.remove(object) // remove by object