Java Collections - TheDavSmasher/softwareconstruction GitHub Wiki

🖥️ Slides

🖥️ Lecture Videos

📖 Required Reading: Core Java for the Impatient

  • Chapter 7: Collections

The Java Collection library provide several useful utility classes for dealing with data structures. This includes things like lists, sets, and maps. Using the standard collections library makes it so that you don't have to write this code yourself. You can also be confident that the code has been thoroughly tested, is secure, and is multithreaded where appropriate.

Collections

Most of the JDK collection objects are contained in the java.util package. It is worth the time to browser the JavaDocs for this package and become familiar with what it offers. Some of the more commonly used interfaces include List, Map, Set, and Iterator. The package also provides various implementations of the interfaces such as HashMap, ArrayList, and TreeSet.

ArrayList Example

Here is an example of using the ArrayList class.

import java.util.ArrayList;

public static class MountainList {
    ArrayList mountains = new ArrayList();

    public MountainList() {
        mountains.add("Nebo");
        mountains.add("Timpanogos");
        mountains.add("Lone Peak");
        mountains.add("Cascade");
        mountains.add("Provo");
        mountains.add("Spanish Fork");
        mountains.add("Santaquin");
    }

    public void print() {
        for (var m : mountains) {
            System.out.println(m);
        }
    }

    public static void main(String[] args) {
        var mountains = new MountainList();
        mountains.print();
    }
}

HashMap Example

Here is an example of using the HashMap class.

import java.util.HashMap;

public static class MountainMap {
    HashMap<String, Integer> mountains = new HashMap<>();

    public MountainMap() {
        mountains.put("Nebo", 11928);
        mountains.put("Timpanogos", 11750);
        mountains.put("Lone Peak", 11253);
        mountains.put("Cascade", 10908);
        mountains.put("Provo", 11068);
        mountains.put("Spanish Fork", 10192);
        mountains.put("Santaquin", 10687);
    }

    public void print() {
        for (var m : mountains.entrySet()) {
            System.out.printf("%s, height: %d%n", m.getKey(), m.getValue());
        }
    }

    public static void main(String[] args) {
        var mountains = new MountainMap();
        mountains.print();
    }
}

Equals and HashCode

When we previously discussed the Java Object class we talked about the importance of overriding the equals and hashCode methods. The JDK collection objects make extensive use of these methods and so it is vital that you implement them on any class that you use with collection objects such as a Map.

Comparable

If you are going to use your objects with collections and operations that sort your objects, you must also implement the Comparable interface. This provides the ability to define the ordering of your object based on the values they contain.

Comparable returns a negative integer if the object is less, zero if they are equal, or a positive integer if the object is greater than the object provided as a parameter to compareTo.

public class ComparableExample implements Comparable<ComparableExample> {
    final private char value;

    ComparableExample(char value) {
        this.value = value;
    }

    @Override
    public int compareTo(ComparableExample o) {
        return value - o.value;
    }

    @Override
    public String toString() {
        return String.format("%c", value);
    }

    public static void main(String[] args) {
        var items = new ComparableExample[]{
            new ComparableExample('r'),
            new ComparableExample('a'),
            new ComparableExample('b')
        };

        Arrays.sort(items);
        for (var i : items) {
            System.out.println(i);
        }
        // Outputs: a b r
    }
}

Things to Understand

  • The interfaces and classes that make up the Java collection API
  • What each interface and class is used for
  • The importance of overriding the equals(...) and hashCode() methods of classes that will be placed in collections
  • The importance of implementing the Comparable interface in classes that will be placed in collections

Videos (42:23)

⚠️ **GitHub.com Fallback** ⚠️