Java, getting an ArrayList index by object

[亡魂溺海] 提交于 2019-12-19 08:51:46

问题


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!


回答1:


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?

Edit:

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




回答2:


Did you look at the indexOf function in ArrayList?




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/12225010/java-getting-an-arraylist-index-by-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!