COLLECTIONS IN JAVA

java-logoBefore talking about collection let’s talk about lists.

LISTS IN JAVA

A list is a list of objects.

Some examples of lists:

  • Television programs of the day
  • Items in an electronic shopping cart
  • Cars passing through the toll plaza.
  • The alumni of a university class
  • The cities of a nation
  • The articles of a constitution
  • The shopping list

There are two types of lists:

Static lists

They have a predefined length that does not change over time.

Dynamic lists

They have an unknown length that may change over time.

To handle lists, Java provides two types of data structures:

Arrays: allow you to manage static lists

Collection: allow you to manage dynamic lists

Arrays we have already dealt with; in this post we will look at Collections.

collection-framework-hierarchy-in-java

WHAT ARE MAPS

A map is a collection of objects identified by a unique key. The main purpose of maps is to manage a number of elements efficiently and quickly.

Le mappe

To manage maps, Java provides, a number of tools to manage dynamic, unordered lists of objects. The maps consist of:

– Interfaces that define useful methods for manipulating collections of objects
– classes implement the interfaces

The classes and interfaces are part of the java.util package. Among the methods for manipulating object maps are those that allow rapid search for elements within the map. The Map interface defines all the methods that must be implemented for proper map management. The main classes that implement the Map interface are:
HashMap – Hashtable – Properties – TreeMap.

When we work with lists (a list of contacts, a list of products, etc.), it often happens that we do not know in advance the number of items to work with. To work with lists we have arrays available. However, if we do not know the number of elements, we cannot initialize an array. Moreover, arrays cannot change their size: the number of elements they contain is determined at the time of initialization and remains unchanged. To go beyond this limitation of arrays, Java provides collections, a set of tools that allow you to manage lists of objects of
variable length. The collections consist of:

– Interfaces that define useful methods for manipulating collections of objects
– classes implement the interfaces

Collection classes and interfaces are part of the java.util package. Methods for manipulating collections of objects include, for example:

– methods for searching for items within the collection
– methods for sorting the elements within the collection

THE ARRAYLIST CLASS

The ArrayList class is a resizable array, located in the java.util package. The difference between an array and an ArrayList in Java is that the size of an array cannot be changed (if you want to add or remove elements to/from an array, you must create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different. The ArrayList class is the implementation of the List interface.

Constructors

– ArrayList<E>() creates an instance of the empty ArrayList class in which the initial capacity is not specified
– ArrayList<E>(int initialCapacity) creates an instance of the ArrayList class in which the initial capacity is specified
The symbol <E>  indicates that when creating a list you can also specify the type of items it is to contain.

Methods

  • Object get(int index) returns the element located at the requested position
  • Object set(int index, Object obj) replaces the element present at the position specified by index with the new element represented by obj
  • boolean add(Object obj) adds the element represented by obj after the last element. The method always returns true.
  • void add(int index, Object obj) inserts the element represented by obj at the position specified by index and moves all other elements that are from the index position onward, advancing them one position.
  • int size() returns the number of elements in the list
  • Object remove(int index) removes the element present at the position specified by index and moves all other elements that are after the one removed, causing them to move back one position
  • int indexOf(Object elem) returns the first position in the list of the element elem, -1 if the element does not exist
  • String toString() returns a string containing the list of items in the list
  • void clear() deletes all items in the list, emptying it completely
  • T[] toArray(T[] a) returns an array containing all the elements of the List
  • boolean isEmpty() returns true if the list is empty, false if the list contains at least one element
package it.corso.java.liste;
import java.util.*;

public class MyArrayList {

    public static void myTestMethodArrayList(){
        ArrayList<String> cars = new ArrayList<String>();
        cars.add("Volvo");
        cars.add("BMW");
        cars.add("Ford");
        cars.add("Mazda");
        System.out.println(cars);
        String ele = cars.get(0);
        System.out.println(ele);
        cars.set(0,"Fiat");
        //ITERAZIONE CON UN CICLO FOR
        for(String s : cars)
            System.out.println(s);
        System.out.println("La dimensione di cars é: " + cars.size());
        int posizione = cars.indexOf("Mazda");
        System.out.println(posizione);
        //ITERAZIONE CON L'INTERFACCIA ITERATOR
        Iterator<String> iterator = cars.iterator();
        while(iterator.hasNext())
            System.out.println(iterator.next());
    }
}

THE LINKEDLIST CLASS

The LinkedList class is a collection that can contain many objects of the same type, just like ArrayList. The LinkedList class has all the same methods as the ArrayList class because they both implement the List interface. This means that you can add items, edit items, remove items and delete the list in the same way. However, the ArrayList class and the LinkedList class are constructed very differently.

HOW THE ARRAYLIST CLASS WORKS

The ArrayList class has a regular array inside it. When an element is added, it is inserted into the array. If the array is not large enough, a new larger array is created to replace the old one and the old one is removed.

HOW THE LINKEDLIST CLASS WORKS

The LinkedList stores its elements in “containers.” The list has a link to the first container, and each container has a link to the next and previous container. To add an item to the list, the item is placed in a new container and that container is linked to one of the other containers in the list.

java-linkedlist-vs-arraylist

In many cases, ArrayList is more efficient since it is common to need to access random elements in the list, but LinkedList provides several methods to perform certain operations very quickly: The figure illustrates these methods.

Method linked list

THE HASHMAP CLASS

A HashMap stores elements in “key/value” pairs, and you can access them via an index of another type (such as a string). An object is used as a key (index) for another object (value). It can store different types: string keys and integer values, or the same type, such as: string keys and string values. Keys and values in a HashMap are actually objects. To use other types, such as int, an equivalent Wrapper class must be specified: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc. The HashMap class is an implementation of the Map interface.

constructors

  • HashMap<K,V>() creates an instance of the empty HashMap class in which the initial capacity is not specified
  • HashMap<K,V>(int initialCapacity) creates an instance of the HashMap class in which the initial capacity is specified

The symbol <K,V> indicates that when creating a map it is also possible to specify the type of element that the key (K) and value (V) are to contain.

Methods

  • Object get (Object key) returns the element associated with the key key
  • Object put(Object key, Object value) adds the value element to the map by associating it with the key key. If the map already contains the key key, the old element is replaced with the new one. The method returns null if the key is not present, or the previous object associated with key
  • Object remove(Object key) removes the element associated with key. The method returns the element that was associated with key before removal
  • int size() returns the number of elements in the map
  • boolean containsKey(Object key) returns true if the map contains an element associated with the searched key, false otherwise
  • void clear() deletes all elements in the map, emptying it completely
  • Set<Object> keySet() returns an object of type Set containing all the keys present in the map
  • boolean isEmpty() returns true if the map is empty, false if the map contains at least one element
hashmap
package it.corso.java.liste;

import java.util.Arrays;
import java.util.HashMap;

public class MyHashMap {

    public static void myTestMethodHashMap() {
        // Create a HashMap object called capitalCities
        HashMap<String, String> capitalCities = new HashMap<String, String>();

        // Add keys and values (Country, City)
        capitalCities.put("England", "London");
        capitalCities.put("Germany", "Berlin");
        capitalCities.put("Norway", "Oslo");
        capitalCities.put("USA", "Washington DC");
        System.out.println(capitalCities);
        System.out.println(capitalCities.get("England"));
        // Print keys
        for (String i : capitalCities.keySet()) {
            System.out.println(i);

        }
        // Print values
        for (String i : capitalCities.values()) {
            System.out.println(i);
        }
        // Print keys and values
        for (String i : capitalCities.keySet()) {
            System.out.println("key: " + i + " value: " + capitalCities.get(i));
        }
        HashMap<String, Integer> people = new HashMap<String, Integer>();


        // Add keys and values (Name, Age)
        people.put("John", 32);
        people.put("Steve", 30);
        people.put("Angie", 33);

        for (String i : people.keySet()) {
            System.out.println("key: " + i + " value: " + people.get(i));
        }
    }
}

HASHSET

A HashSet is a collection of elements where each element is unique and is found in the java.util package:

JAVA ITERATOR

An Iterator is an object that can be used to step through collections, such as ArrayLists and HashSets. It is called “iterator” because “iterate” is the technical term for the cycle.

The Iterator<E> interface is located in the java.util package and is an interface for generating classes for iterating the elements of a Collection.

The interface defines 3 methods:

  • hasNext() returns true as long as there are list items to scroll through
  • next() returns the next element
  • remove() removes the last returned element from the list.

The remove() method must be used only during a loop on the elements, otherwise Java throws the ConcurrentModificationException when we next access the list. The Collection, List, Set interfaces and their implementing classes (e.g., ArrayList) contain the iterator() method that returns an object of type Iterator<E>. Through the iterator() method, it is possible to cycle through all the elements of a list.

LINKS TO PREVIOUS POSTS

THE JAVA LANGUAGE

LINK TO CODE ON GITHUB

GITHUB

EXECUTION OF THE EXAMPLE CODE

  • Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.

         java -jar –enable-preview CorsoJava.jar

  • Or run the main found in the file CorsoJava.java.