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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:06:38  来源:igfitidea点击:

Java, getting an ArrayList index by object

javaarraylist

提问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

why don't you simply use this.name? As you already have the object why do you need to get the index to again get the object?

你为什么不简单地使用 this.name ?既然已经有了对象,为什么还需要获取索引才能再次获取对象?

Edit:

编辑:

To answer the question in the title(to get index of the object) use indexOf

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

回答by randominstanceOfLivingThing

Did you look at the indexOffunction in ArrayList?

你看ArrayList中的indexOf函数了吗?

回答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