Week 6

Objects containing a list

Let's take a look at objects that contain a list, such as those that describe sets, for instance, playlists.

Here's an example of a class we've created for the concept of a playlist. The playlist contains songs, which can be added or removed, and the songs it contains can be printed.

// imports

public class Playlist {
    private List<String> songs;

    public Playlist() {
        this.songs = new ArrayList<>();
    }

    public void addSong(String song) {
        this.songs.add(song);
    }

    public void removeSong(String song) {
        this.songs.remove(song);
    }

    public void printSongs() {
        for (String song: this.songs) {
            System.out.println(song);
        }
    }
}

Creating a playlist is easy with the help of the class above.

Playlist list = new Playlist();
list.addSong("Killer Queen");
list.addSong("Crazy Little Thing Called Love");
list.printSongs();
Sample output

Killer Queen Crazy Little Thing Called Love

Loading

Objects in an Instance Variable List

In the previous section, we created an AmusementParkRide class to verify if a person met the requirements to go on a specific ride. Here's an example of how the AmusementPark class might look like:

public class AmusementParkRide {
    private String name;
    private int minimumHeight;
    private int visitors;

    public AmusementParkRide(String name, int minimumHeight) {
        this.name = name;
        this.minimumHeight = minimumHeight;
        this.visitors = 0;
    }

    public boolean isAllowedOn(Person person) {
        if (person.getHeight() < this.minimumHeight) {
            return false;
        }

        this.visitors++;
        return true;
    }

    public String toString() {
        return this.name + ", minimum height requirement: " + this.minimumHeight +
            ", visitors: " + this.visitors;
    }
}

Let's expand the AmusementParkRide class to include a feature that keeps track of the people who are on the ride. For this updated version, the ride will have an instance variable that represents a list of the people who have been allowed on the ride. This list will be created in the constructor.

public class AmusementParkRide {
    private String name;
    private int minimumHeigth;
    private int visitors;
    private List<Person> riding;

    public AmusementParkRide(String name, int minimumHeigth) {
        this.name = name;
        this.minimumHeigth = minimumHeigth;
        this.visitors = 0;
        this.riding = new ArrayList<>();
    }

    // ..
}

Let's change the method isAllowedOn. The method adds to the list all the persons who meet the height requirements.

public class AmusementParkRide {
    private String name;
    private int minimumHeight;
    private int visitors;
    private List<Person> riding;

    public AmusementParkRide(String name, int minimumHeight) {
        this.name = name;
        this.minimumHeight = minimumHeight;
        this.visitors = 0;
        this.riding = new ArrayList<>();
    }

    public boolean isAllowedOn(Person person) {
        if (person.getHeight() < this.minimumHeight) {
            return false;
        }

        this.visitors++;
        this.riding.add(person);
        return true;
    }

    public String toString() {
        return this.name + ", minimum height requirement: " + this.minimumHeight +
            ", visitors: " + this.visitors;
    }
}
Loading

Printing an Object from a List

Let's now modify the toString method such that the string returned by the method contains the name of each and every person on the ride.

public class AmusementParkRide {
    private String name;
    private int minimumHeight;
    private int visitors;
    private List<Person> riding;

    // ...

    public String toString() {
        // let's form a string from all the people on the list
        String onTheRide = "";
        for (Person person: riding) {
            onTheRide = onTheRide + person.getName() + "\n";
        }

        // we return a string describing the object
        // including the names of those on the ride
        return this.name + ", minimum height requirement: " + this.minimumHeight +
            ", visitors: " + this.visitors + "\n" +
            "riding:\n" + onTheRide;
    }
}

Let's test out the extended amusement park ride:

Person matti = new Person("Matti");
matti.setWeigth(86);
matti.setHeight(180);

Person juhana = new Person("Juhana");
juhana.setWeigth(34);
juhana.setHeight(132);

AmusementParkRide hurjakuru = new AmusementParkRide("Hurjakuru", 140);
System.out.println(hurjakuru);

System.out.println();

if (hurjakuru.isAllowedOn(matti)) {
    System.out.println(matti.getNimi() + " is allowed on the ride");
} else {
    System.out.println(matti.getNimi() + " is not allowed on the ride");
}

if (hurjakuru.isAllowedOn(juhana)) {
    System.out.println(juhana.getNimi() + " is allowed on the ride");
} else {
    System.out.println(juhana.getNimi() + " is not allowed on the ride");
}

System.out.println(hurjakuru);

The program's output is:

Sample output

Hurjakuru, minimum height requirement: 140, visitors: 0 riding:

Matti is allowed on the ride Juhana is not allowed on the ride Hurjakuru, minimum height requirement: 140, visitors: 1 riding: Matti

Currently, the toString method of the AmusementParkRide class always outputs the string riding:, even if there are no riders on the ride. To handle this case and inform the user that there are no riders on the ride, we can modify the toString method.

public class AmusementParkRide {
    private String name;
    private int minimumHeight;
    private int visitors;
    private List<Person> kyydissa;

    public AmusementParkRide(String name, int minimumHeight) {
        this.name = name;
        this.minimumHeight = minimumHeight;
        this.visitors = 0;
        this.riding = new ArrayList<>();
    }

    // ...

    public String toString() {

        String printOutput = this.name + ", minimum height requirement: " + this.minimumHeight +
            ", visitors: " + this.visitors + "\n";

        if (riding.isEmpty()) {
            return printOutput + "no one is on the ride.";
        }

        // we form a string from the people on the list
        String peopleOnRide = "";

        for (Person person: riding) {
            peopleOnRide = peopleOnRide + person.getName() + "\n";
        }

        return printOutput + "\n" +
            "on the ride:\n" + peopleOnRide;
    }
}

The print output has now been improved.

Person matti = new Person("Matti");
matti.setWeight(86);
matti.setHeight(180);

Person juhana = new Person("Juhana");
juhana.setWeight(34);
juhana.setHeight(132);

AmusementParkRide hurjakuru = new AmusementParkRide("Hurjakuru", 140);
System.out.println(hurjakuru);

System.out.println();

if (hurjakuru.isAllowedOn(matti)) {
    System.out.println(matti.getName() + " is allowed on the ride");
} else {
    System.out.println(matti.getName() + " is not allowed on the ride");
}

if (hurjakuru.isAllowedOn(juhana)) {
    System.out.println(juhana.getName() + " is allowed on the ride");
} else {
    System.out.println(juhana.getName() + " is not allowed on the ride");
}

System.out.println(hurjakuru);

The program's output is:

Sample output

Hurjakuru, minimum height requirement: 140, visitors: 0 no one is on the ride.

Matti is allowed on the ride Juhana is not allowed on the ride Hurjakuru, minimum height requirement: 140, visitors: 1 on the ride: Matti

Loading

Clearing an Object's List

We'll next add a removeEveryoneOnRide method to the amusement park ride, which removes each and every person currently on the ride.The list method clear is very handy here.

public class AmusementParkRIde {
    // ..

    public void removeEveryoneOnRide() {
        this.riding.clear();
    }

    // ..
}
Person matti = new Person("Matti");
matti.setWeight(86);
matti.setHeight(180);

Person juhana = new Person("Juhana");
juhana.setWeight(34);
juhana.setHeight(132);

AmusementParkRide hurjakuru = new AmusementParkRide("Hurjakuru", 140);
System.out.println(hurjakuru);

System.out.println();

if (hurjakuru.isAllowedOn(matti)) {
    System.out.println(matti.getName() + " is allowed on the ride");
} else {
    System.out.println(matti.getName() + " is not allowed on the ride");
}

if (hurjakuru.isAllowedOn(juhana)) {
    System.out.println(juhana.getName() + " is allowed on the ride");
} else {
    System.out.println(juhana.getName() + " is not allowed on the ride");
}

System.out.println(hurjakuru);

hurjakuru.removeEveryoneOnRide();

System.out.println();
System.out.println(hurjakuru);

The program's output is:

Sample output

Hurjakuru, minimum height requirement: 140, visitors: 0 no one is on the ride.

Matti is allowed on the ride. Juhana is not allowed on the ride Hurjakuru, minimum height requirement: 140, visitors: 1 on the ride: Matti

Hurjakuru, minimum height requirement: 140, visitors: 1 no one is on the ride.

Calculating a Sum from Objects on a List

Let's create a method for the amusement park ride that calculates the average height of the people currently on it. To obtain the average height, we need to add up the heights of all the persons on the ride and divide the sum by the number of persons.

If there are no persons on the ride, the method should return -1. However, returning -1 as the average height is impossible in a program that calculates averages. Therefore, if the method returns -1, we can determine that the average height could not have been calculated.

public class AmusementParkRide {
    private String name;
    private int minimumHeight;
    private int visitors;
    private List<Person> riding;

    // ..

    public double averageHeightOfPeopleOnRide() {
        if (riding.isEmpty()) {
            return -1;
        }

        int sumOfHeights = 0;
        for (Person per: riding) {
            sumOfHeights += per.getHeight();
        }

        return 1.0 * sumOfHeights / riding.size();
    }

    // ..
}
Person matti = new Person("Matti");
matti.setHeight(180);

Person juhana = new Person("Juhana");
juhana.setHeight(132);

Person awak = new Henkilo("Awak");
awak.setHeight(194);

AmusementParkRide hurjakuru = new AmusementParkRide("Hurjakuru", 140);

hurjakuru.isAllowedOn(matti);
hurjakuru.isAllowedOn(juhana);
hurjakuru.isAllowedOn(awak);

System.out.println(hurjakuru);
System.out.println(hurjakuru.averageHeightOfPeopleOnRide());

The program's output is:

Sample output

Hurjakuru, minimum height requirement: 140, visitors: 2 on the ride: Matti Awak 187.0

Loading

Retrieving a Specific Object from a List

Now, let's create a method for the amusement park ride that returns the tallest person on the ride. The method should retrieve the tallest person from the list and return it.

When implementing methods that retrieve objects from a list, we follow a specific approach. First, we check whether the list is empty. If it is, we return a null reference or some other value indicating that the list has no values. Next, we create an object reference variable that describes the object to be returned and initialize it to the first object on the list.

We then iterate through the values on the list by comparing each list object with the object variable representing the object to be returned. If a better matching object is found, it is assigned to the object reference variable to be returned. Finally, we return the object variable describing the object that we want to return.

public Person getTallest() {
    // return a null reference if there's no one on the ride
    if (this.riding.isEmpty()) {
        return null;
    }

    // create an object reference for the object to be returned
    // its first value is the first object on the list
    Person returnObject = this.riding.get(0);

    // go through the list
    for (Person prs: this.riding) {
        // compare each object on the list
        // to the returnObject -- we compare heights
        // since we're searching for the tallest,

        if (returnObject.getHeight() < prs.getHeight()) {
            // if we find a taller person in the comparison,
            // we assign it as the value of the returnObject
            returnObject = prs;
        }
    }

    // finally, the object reference describing the
    // return object is returned
    return returnObject;
}

Finding the tallest person is now easy.

Person matti = new Person("Matti");
matti.setHeight(180);

Person juhana = new Person("Juhana");
juhana.setHeight(132);

Person awak = new Person("Awak");
awak.setHeight(194);

AmusementParkRide hurjakuru = new AmusementParkRide("Hurjakuru", 140);

hurjakuru.isAllowedOn(matti);
hurjakuru.isAllowedOn(juhana);
hurjakuru.isAllowedOn(awak);

System.out.println(hurjakuru);
System.out.println(hurjakuru.averageHeightOfPeopleOnRide());

System.out.println();
System.out.println(hurjakuru.getTallest().getName());
Person tallest = hurjakuru.getTallest();
System.out.println(tallest.getName());
Sample output

Hurjakuru, minimum height requirement: 140, visitors: 2 on the ride: Matti Awak 187.0

Awak Awak

Loading
You have reached the end of this section! Continue to the next section: