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
.
pop() function. The simplest approach is to use the list's pop([i]) function, which removes an element present at the specified position in the list. If we don't specify any index, pop() removes and returns the last element in the list.
remove() Method. Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj).
The size() method returns the number of elements in the ArrayList. The index values of the elements are 0 through (size()-1) , so you would use myArrayList. get(myArrayList. size()-1) to retrieve the last element.
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.
The compiler complains that you are trying something of a list of ClientThread
objects to a String
. Either change the type of hey
to ClientThread
or clients
to List<String>
.
In addition: Valid indices for lists are from 0 to size()-1.
So you probably want to write
String hey = clients.get(clients.size()-1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With