Java - java.util.Collection Interface

Introduction

The java.util.Collection interface is the root of the collection interface hierarchy.

It is the most generic type of collection.

Methods for Basic Operations

Methods for basic operations let you perform basic operations on a collection such as:

  • getting its size (number of elements),
  • adding a new element to it,
  • removing an element from it,
  • checking if an object is an element of this collection,
  • checking if the collection is empty, etc.

Example

The program uses the add() method to add some names to a collection.

It uses the remove() method to remove a name from the list.

The clear() method is used to remove all names from the list.

The program prints the size of the list and the elements in the list.

toString() method of the collection returns a comma-separated list of elements enclosed in brackets.

If a collection is empty, an empty pair of brackets [] is returned.

Demo

import java.util.ArrayList;
import java.util.Collection;

public class Main {
  public static void main(String[] args) {
    // Create a list of strings
    Collection<String> names = new ArrayList<>();

    // Print the list details
    System.out.printf("After creation: Size = %d, Elements = %s%n", names.size(), names);

    // Add some names to the list
    names.add("Java");
    names.add("Javascript");
    names.add("Joe");

    // Print the list details
    System.out.printf("After adding 3 elements: Size = %d, Elements = %s%n", names.size(), names);

    // Remove Javascript from the list
    names.remove("Javascript");

    // Print the list details
    System.out.printf("After removing 1 element: Size = %d, Elements = %s%n", names.size(), names);

    // Clear all elements
    names.clear();/*from  w w  w .  ja v  a2  s . c  o m*/

    // Print the list details
    System.out.printf("After clearing all elements: Size = %d, Elements = %s%n", names.size(), names);

  }
}

Result

Related Topics