Computer >> Computer tutorials >  >> Programming >> Java

Java Program to Use Different Types of a Collection


In this article, we will understand how to use different types of a collection.

Below is a demonstration of the same −

Suppose our input is

Input list: [101, 102, 103, 104, 105]

The desired output would be

The list after removing an element:
101 102 103 105

Algorithm

Step 1 - START
Step 2 - Declare a list namely input_collection.
Step 3 - Define the values.
Step 4 - Using the function remove(), we send the index value of the element as parameter, we remove the specific element.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we show the use of ArrayList. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

import java.util.*;
public class Demo {
   public static void main(String[] args){
      ArrayList<Integer> input_collection = new ArrayList<Integer>();
      for (int i = 1; i <= 5; i++)
      input_collection.add(i + 100);
      System.out.println("The list is defined as: " +input_collection);
      input_collection.remove(3);
      System.out.println("\nThe list after removing an element: ");
      for (int i = 0; i < input_collection.size(); i++)
      System.out.print(input_collection.get(i) + " ");
   }
}

Output

The list is defined as: [101, 102, 103, 104, 105]

The list after removing an element:
101 102 103 105

Example 2

Here, we show the use of linked list. The java.util.LinkedList class operations perform we can expect for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

import java.util.*;
public class Demo {
   public static void main(String[] args){
      LinkedList<Integer> input_collection = new LinkedList<Integer>();
      for (int i = 1; i <= 5; i++)
      input_collection.add(i + 100);
      System.out.println("The list is defined as: " +input_collection);
      input_collection.remove(3);
      System.out.println("\nThe list after removing an element");
      for (int i = 0; i < input_collection.size(); i++)
      System.out.print(input_collection.get(i) + " ");
   }
}

Output

The list is defined as: [101, 102, 103, 104, 105]

The list after removing an element
101 102 103 105