Free Data Structures and Algorithms Course

Subscribe below and get all best seller courses for free !!!


Subscribe to all free courses

How to hold your objects using Collection Interface in Java ?

Program to demonstrate how to hold your objects using Collection Interface in Java

package com.hubberspot.example;

// 1. We have to import two Collections
// framework class and interface as 
// ArrayList and Collection

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

public class CollectionDemo {

 public static void main(String[] args) {

  // 2. Creating a Collection reference variable
  // for holding the objects. Collection is interface
  // which is the base interface for all the collections
  // such as ArrayList, Queue etc. Here we have created 
  // an ArrayList object which is holding the String objects
  // and its object is been referenced by Collection 

  Collection<String> collections = new ArrayList<String>(); 

  // 3. Adding five String objects to Collection such as 
  // "www", ".", "hubberspot", ".", "com"

  System.out.println("The Collection objects are : ");

  // 4. Looping each Collection object and printing it on 
  // console

  for(String s : collections) {



Output of the program :

© 2021 Learn Java by Examples Template by Hubberspot