OK, so here is my ArrayList
:
private List clients = new ArrayList();
and here is what I am
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!
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);
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.