Java - remove last known item from ArrayList

前端 未结 3 754
暖寄归人
暖寄归人 2021-02-11 16:39

OK, so here is my ArrayList:

private List clients = new ArrayList();

and here is what I am

3条回答
  •  醉酒成梦
    2021-02-11 17:10

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

    private List clients = new ArrayList();
    

    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 clients = new ArrayList();
    
        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!

提交回复
热议问题