Java Collections Framework

When you have a large number of objects of same or different type, that you want to store and retrieve in memory, you need a way to structure and manage them. In Computer Science, you will learn about the term Data Structures which precisely help you organize, modify and retrieve a large collection of data. In Java, Collections Framework provides us with many different types of Data Structures with each one having its specific advantages over the other. The choice of which data structure to use depends upon your application and what you are trying to accomplish. You will learn about some of the common collection types in this lesson.

ArrayList

In earlier lessons, you already learnt about arrays. Arrays are great, however, before you start adding elements into the array, you have to declare the size of the array. Compared to an array, ArrayList has the following advantages:

  • Size of the ArrayList need not be declared. Whereas in arrays, you have to declare the size before you can start adding elements into it.
  • ArrayList increases its size as and when elements are added so you can add or remove items without worrying about the size of the ArrayList. In array, you cannot add elements beyond the declared size.
  • Many convenience methods are provided which makes working with ArrayList really easy. E.g., you can use sort() method on ArrayList to sort the elements in the ArrayList etc..

ArrayList syntax:

ArrayList<E> mylist = new ArrayList<E>();

where E is the type of element that the ArrayList is going to hold. E can be replaced by any object type like String, Integer etc., E cannot be a primitive type like int, long etc..

Note however that ArrayList is still a wrapper around the basic array structure. A wrapper is nothing but an object which contains another object. In this case ArrayList wrapper contains an inner array. The inner array actually holds the ArrayList objects. So when more elements are added beyond the size of the inner array, the wrapper ArrayList object automatically creates a new larger array and copies over from the old one and then discards the old array. All these operations are transparent to you and you need not worry about it.

ArrayList implements List interface. You will learn about Interfaces in the next lesson. All collection classes belong to java.util package. Refer to the JavaDoc for ArrayList to learn more on the convenience methods and the various constructors.: https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html

Examples:

import java.util.ArrayList;

public class ArrayListDemo{

    public static void main(String[] args){

        ArrayList<String> favoriteFruits = new ArrayList<String>();
        favoriteFruits.add("Mango");
        favoriteFruits.add("Banana");
        favoriteFruits.add("Apple");

        System.out.println(favoriteFruits);

        favoriteFruits.remove("Apple");
        System.out.println(favoriteFruits);

        for (String favoriteFruit : favoriteFruits) {
            System.out.println(favoriteFruit);

        }

        favoriteFruits.add("Banana");
        System.out.println(favoriteFruits);
    }
}

Output

[Mango, Banana, Apple]
[Mango, Banana]
Mango
Banana
[Mango, Banana, Banana]

Notice the foreach loop in the above examples. With all collections you can use the foreach loop to iterate over all elements of the collection. Also notice that duplicate 'Banana' is added to the ArrayList without any problem.

HashSet

HashSet implements Set interface. In a set, you cannot have duplicate items. In the ArrayList duplicates are allowed but not in a Set.

ArrayList syntax:

HashSet<E> myset = new HashSet<E>();

Here also E represents any type of object.

Here is the ArrayList example implemented in a set:

import java.util.HashSet;

public class HashSetDemo{

    public static void main(String[] args){

        HashSet<String> favoriteFruits = new HashSet<String>();
        favoriteFruits.add("Mango");
        favoriteFruits.add("Banana");
        favoriteFruits.add("Apple");

        System.out.println(favoriteFruits);

        favoriteFruits.remove("Apple");
        System.out.println(favoriteFruits);

        for (String favoriteFruit : favoriteFruits) {
            System.out.println(favoriteFruit);

        }

        favoriteFruits.add("Banana");
        System.out.println(favoriteFruits);
    }
}

Output:

[Mango, Apple, Banana]
[Mango, Banana]
Mango
Banana
[Mango, Banana]

Notice the duplicate 'Banana' is not added. You use a Set when you do not want any duplicates to be added. Along with duplicates, a Set does not keep the order in which the elements were added/removed. If you want strict order, then you have to use ArrayList which maintains the order of elements. Javadoc for HashSet: https://docs.oracle.com/javase/9/docs/api/java/util/HashSet.html

HashMap

HashMap implements Map interface. In Map you keep name/value pairs instead of a collection of one type of objects. A key can be of any object type. Keys are unique in HashMap. If you try to add a duplicate key/value, then the existing value for the key will be replaced with the new value.

HashMap syntax:

HashMap<E,E> myMap = new HashMap<E,E>()

Here is an example implementation of HashMap

import java.util.HashMap;

public class HashMapDemo{

    public static void main(String[] args){

        HashMap<String, String> countryCodes = new HashMap<String, String>();
        countryCodes.put("US", "United States");
        countryCodes.put("MX", "Mexico");
        countryCodes.put("CA", "Canada");

        System.out.println(countryCodes);

        System.out.println(countryCodes.get("US"));
    }
}

Output:

{MX=Mexico, US=United States, CA=Canada}
United States

Notice that you use put in HashMap instead of add. Both structures provide get method. get in HashMap receives the name and returns the value

In HashMap you can iterate over the names or values. Here is an example of using foreach to print out the HashMap's key/value pairs.

import java.util.HashMap;
import java.util.Map;

public class HashMapDemo{

    public static void main(String[] args){

        HashMap<String, String> countryCodes = new HashMap<String, String>();
        countryCodes.put("US", "United States");
        countryCodes.put("MX", "Mexico");
        countryCodes.put("CA", "Canada");

       for (Map.Entry<String, String> countryCode : countryCodes.entrySet()) {
               String key = countryCode.getKey();
            String value = countryCode.getValue();
            System.out.println("key:"+key + ", value:" + value);
        }
    }
}

Output:

key:MX, value:Mexico
key:US, value:United States
key:CA, value:Canada

You can iterate over keys and values individually also. map.keySet() will provide a set of keys. map.values() will give a collection of values.

Javadoc for HashMap: https://docs.oracle.com/javase/9/docs/api/java/util/HashMap.html

results matching ""

    No results matching ""