Java,按对象获取 ArrayList 索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12225010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java, getting an ArrayList index by object
提问by Jeremy Sayers
so I have hit a little problem in my code I have:
所以我在我的代码中遇到了一个小问题:
synchronized(clients)
clients.remove(this);
}
for when a client disconnects, but now I need to be able to send the name of that client to all the other clients, and to do this I essentialy need to do something like
因为当客户端断开连接时,但现在我需要能够将该客户端的名称发送给所有其他客户端,为此我基本上需要做一些类似的事情
synchronized(clients)
broadcast("Remove:"+clients.get(this).name);
clients.remove(this);
}
but obviously I can't get an index with the "this", so how do I go about getting the right clients name? Thanks!
但显然我无法获得带有“this”的索引,那么我该如何获得正确的客户名称呢?谢谢!
回答by Ankur
回答by randominstanceOfLivingThing
回答by MadProgrammer
int index = clients.indexOf(this);
// Do what ever...
clients.remove(index); // or clients.remove(this);
回答by Mohammod Hossain
I think you want to remove specific object from list. If you get index from your code
我认为您想从列表中删除特定对象。如果您从代码中获得索引
int index = clients.get(this)
Then you can remove easily
然后你可以轻松删除
clients.remove(index);
or if you get object from list then remove
或者如果您从列表中获取对象然后删除
clients.remove(object) // remove by object