nn2 nn2 - 5 months ago 12
Java Question

Java - remove last known item from ArrayList

OK, so here is my

ArrayList
:

private List<ClientThread> clients = new ArrayList<ClientThread>();


and here is what I am trying to do:

I am trying to remove the last known item from the
ArrayList
I posted above. I'm trying to do this with the code below:

} catch(SocketException re) {


String hey = clients.get(clients.size());
ClientThread.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());
}


but I am getting this error:

C:\wamp\www\mystikrpg\Server.java:147: incompatible types
found : Server.ClientThread
required: java.lang.String
String hey = clients.get(clients.size());
^
C:\wamp\www\mystikrpg\Server.java:148: cannot find symbol
symbol : method remove(java.lang.String)
location: class Server.ClientThread
ClientThread.remove(hey);
^
2 errors


What am I doing wrong?
It's supposed to remove the last known item from my
ArrayList
.

Answer

It should be:

ClientThread hey = clients.get(clients.size() - 1);
clients.remove(hey);

Or you can do

clients.remove(clients.size() - 1);

The minus ones are because size() returns the number of elements, but the ArrayList's first element's index is 0 and not 1.

Comments