Object-Oriented Programming with Java, part I – Exercise 62

This program uses the method public static void removeLast(ArrayList<String> list) to remove the last item from the list.

My Code

import java.util.ArrayList;
import java.util.Collections;

public class RemoveLast {
    public static void removeLast(ArrayList<String> list) {
        list.remove(list.size() -1);
    }

    public static void main(String[] args) {
        // Here an example what you can do with the method 
        ArrayList<String> persons = new ArrayList<String>();
        persons.add("Pekka");
        persons.add("James");
        persons.add("Liz");
        persons.add("Brian");

        System.out.println("Persons:");
        System.out.println(persons);

        // sort the persons
        Collections.sort(persons);

        // and remove the last
        removeLast(persons);

        System.out.println(persons);
    }
}

Model Code

import java.util.ArrayList;

import java.util.Collections;

 

public class RemoveLast {

    public static void removeLast(ArrayList<String> list) {

        int indexOfLast = list.size()-1;

        list.remove(indexOfLast);

    }

 

    public static void main(String[] args) {

        // Here an example what you can do with the method 

        ArrayList<String> persons = new ArrayList<String>();

        persons.add("Pekka");

        persons.add("James");

        persons.add("Liz");

        persons.add("Brian");

 

        System.out.println("Persons:");

        System.out.println(persons);

 

        // sort the persons

        Collections.sort(persons);

 

        // and remove the last

        removeLast(persons);

 

        System.out.println(persons);

    }

}

Comments

I am mildly proud of that although at this rate it is going to take a year to write anything large. Shorter than the model code anyway.

Leave a comment