Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - remove last known item from ArrayList

Tags:

java

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.

like image 271
test Avatar asked Aug 18 '10 18:08

test


People also ask

How do I remove the last element in a list?

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.

How do you remove an element from an ArrayList in Java?

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).

How do you find the last element of an ArrayList?

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.


2 Answers

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.

like image 119
jonescb Avatar answered Sep 18 '22 17:09

jonescb


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); 
like image 45
Andre Holzner Avatar answered Sep 22 '22 17:09

Andre Holzner