[java] 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.

This question is related to java arraylist

The answer is


First error: You're casting a ClientThread as a String for some reason.

Second error: You're not calling remove on your List.

Is is homework? If so, you might want to use the tag.


You're trying to assign the return value of clients.get(clients.size()) to the string hey, but the object returned is a ClientThread, not a string. As Andre mentioned, you need to use the proper index as well.

As far as your second error is concerned, there is no static method remove() on the type ClientThread. Really, you likely wanted the remove method of your List instance, clients.

You can remove the last item from the list, if there is one, as follows. Since remove also returns the object that was removed, you can capture the return and use it to print out the name:

int size = clients.size();

if (size > 0) {
    ClientThread client = clients.remove(size - 1);

    System.out.println(client + " has logged out.");
    System.out.println("CONNECTED PLAYERS: " + clients.size());
}

You need to understand java generics. You have a list of ClientThread but trying to get String. You have other errors, but this one is very basic.


This line means you instantiated a "List of ClientThread Objects".

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

This line has two problems.

String hey = clients.get(clients.size());

1. This part of the line:

clients.get(clients.size());

ALWAYS throws IndexOutOfBoundsException because a collections size is always one bigger than its last elements index;

2. Compiler complains about incompatible types because you cant assign a ClientThread object to String object. Correct one should be like this.

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

Last but not least. If you know index of the object to remove just write

 clients.remove(23); //Lets say it is in 23. index

Don't write

   ClientThread hey = clients.get(23); 

   clients.remove(hey);

because you are forcing the list to search for the index that you already know. If you plan to do something with the removed object later. Write

   ClientThread hey = clients.remove(23); 

This way you can remove the object and get a reference to it at the same line.

Bonus: Never ever call your instance variable with name "hey". Find something meaningful.

And Here is your corrected and ready-to-run code:

public class ListExampleForDan {

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

    public static void main(String args[]) {

        clients.add(new ClientThread("First and Last Client Thread"));

        boolean success = removeLastElement(clients);

        if (success) {

            System.out.println("Last Element Removed.");

        } else {

            System.out.println("List Is Null/Empty, Operation Failed.");

        }

    }

    public static boolean removeLastElement(List clients) {

        if (clients == null || clients.isEmpty()) {

            return false;

        } else {

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

            return true;

        }

    }
}

Enjoy!


clients.get will return a ClientThread and not a String, and it will bomb with an IndexOutOfBoundsException if it would compile as Java is zero based for indexing.

Similarly I think you should call remove on the clients list.

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

I would use the stack functions of a LinkedList in this case though.

ClientThread hey = clients.removeLast()

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