You are on page 1of 27

A collection represents a group of objects, known as its elements.

This framework is
provided in the java.util package. Objects can be stored, retrieved, and
manipulated as elements of collections. Collection is a Java Interface. Collections
can be used in various scenarios like Storing phone numbers, Employee names
database etc. They are basically used to group multiple elements into a single unit.
Some collections allow duplicate elements while others do not. Some collections are
ordered and others are not.

A Collections Framework mainly contains the following 3 parts

A Collections Framework is defined by a set of interfaces, concrete class


implementations for most of the interfaces and a set of standard utility methods
and algorithms. In addition, the framework also provides
severalabstract implementations, which are designed to make it easier for you to
create new and different implementations for handling collections of data.

Core Collection Interfaces


The core interfaces that define common functionality and allow collections to be
manipulated independent of their implementation.
The 6 core Interfaces used in the Collection framework are:

 Collection
 Set

 List

 Iterator (Not a part of the Collections Framework)

 SortedSet

 Map

 SortedMap

Note: Collection and Map are the two top-level interfaces.


Collection Interface
Map Interface

Concrete Classes
The concrete classes that are specific implementations of the core interfaces, providing data structures
that a java program can use.
Note: Concrete Classes for the Map is shown in the previous section.
Standard utility methods and algorithms

Standard utility methods and algorithms

that can be used to perform various operations on collections, such as


sorting, searching or creating customized collections.

How are Collections Used


 The collections stores object references, rather than objects themselves.
Hence primitive values cannot be stored in a collection directly. They need to
be encapsulated (using wrapper classes) into an Object prior to storing them
into a Collection (such as HashSet, HashMap etc).
 The references are always stored as type Object. Thus, when you retrieve an
element from a collection, you get an Object rather then the actual type of
the collection stored in the database. Hence we need to downcast it to the
Actual Type while retrieving an element from a collection.

 One of the capabilities of the Collection Framework is to create a


new Collection object and populate it with the contents of an
existing Collection object of a same or different actual type.

Below is an example program showing the storing and retrieving of a few Collection Types

import java.util.*;

public class CollectionsDemo {

public static void main(String[] args) {


List a1 = new ArrayList();
a1.add("Beginner");
a1.add("Java");
a1.add("tutorial");
System.out.println(" ArrayList Elements");
System.out.print("\t" + a1);
List l1 = new LinkedList();
l1.add("Beginner");
l1.add("Java");
l1.add("tutorial");
System.out.println();
System.out.println(" LinkedList Elements");
System.out.print("\t" + l1);
Set s1 = new HashSet(); // or new TreeSet() will order the elements;
s1.add("Beginner");
s1.add("Java");
s1.add("Java");
s1.add("tutorial");
System.out.println();
System.out.println(" Set Elements");
System.out.print("\t" + s1);
Map m1 = new HashMap(); // or new TreeMap() will order based on keys
m1.put("Windows", "98");
m1.put("Win", "XP");
m1.put("Beginner", "Java");
m1.put("Tutorial", "Site");
System.out.println();
System.out.println(" Map Elements");
System.out.print("\t" + m1);
}
}

Output

ArrayList Elements
[Beginner, Java, tutorial]
LinkedList Elements
[Beginner, Java, tutorial]
Set Elements
[tutorial, Beginner, Java]
Map Elements
{Tutorial=Site, Windows=98, Win=XP, Beginner=Java}

Advantages of collections framework:

1. We need not to learn multiple ad hoc collection APIs.


2. It provides a standard interface for collections that fosters software reuse and also
provides algorithms to manipulate them.

3. Reduces the effort required to design and implement APIs by eliminating the need to
produce ad hoc collections APIs.

4. It provides useful data structures and algorithms that reduces programming effort due to
which we need not to write them ourselves.

5. It provides high-performance implementations of useful data structures and algorithms


that increases the performance.

6. Helps in establishing a common language to pass collections back and forth that provides
interoperability between unrelated APIs.
7. Collection is resizable and can grow.

Disadvantages of collections framework:

1. It must cast to correct type.


2. It can't be done compile-time type checking.

Description:

Here we can see example for basic ArrayList operations like creating object for ArrayList, adding objects into ArrayList, ac
objects based on index, searching an object in ArrayList whether it is listed under this instance or not, adding elements at s
checking whether the ArrayList is empty or not, getting object index, and finally size of the ArrayList.

Code:
?
1
2
3 package com.java2novice.arraylist;
4
import java.util.ArrayList;
5
6 public class MyBasicArrayList {
7
8 public static void main(String[] a){
9
10 ArrayList<String> al = new ArrayList<String>();
11 //add elements to the ArrayList
12 al.add("JAVA");
al.add("C++");
13 al.add("PERL");
14 al.add("PHP");
15 System.out.println(al);
16 //get elements by index
System.out.println("Element at index 1: "+al.get(1));
17
System.out.println("Does list contains JAVA? "+al.contains("JAVA"));
18 //add elements at a specific index
19 al.add(2,"PLAY");
20 System.out.println(al);
21 System.out.println("Is arraylist empty? "+al.isEmpty());
System.out.println("Index of PERL is "+al.indexOf("PERL"));
22 System.out.println("Size of the arraylist is: "+al.size());
23 }
24 }
25
26
Output:
[JAVA, C++, PERL, PHP]
Element at index 1: C++
Does list contains JAVA? true
[JAVA, C++, PLAY, PERL, PHP]
Is arraylist empty? false
Index of PERL is 3
Size of the arraylist is: 5
Program: How to read all elements in ArrayList by using iter

Description:

Here we can see example for reading all elements from ArrayList by using Iterator. Also you can iterate through the ArrayL
index too.

Code:

1 package com.java2novice.arraylist;

3 import java.util.ArrayList;

import java.util.Iterator;
4

5
public class ArrayListIterator {
6

7
public static void main(String a[]){
8
ArrayList<String> arrl = new ArrayList<String>();
9
//adding elements to the end
10
arrl.add("First");
11
arrl.add("Second");
12 arrl.add("Third");

13 arrl.add("Random");

14 Iterator<String> itr = arrl.iterator();

15 while(itr.hasNext()){

System.out.println(itr.next());
16
}
17
}
18

19 }

20

Output:

First
Second
Third
Random
Program: How to copy or clone a ArrayList?

Description:

Here we can see example for creating duplicate object of an ArrayList instance. we can done this by using clone() function

Code:

package com.java2novice.arraylist;

import java.util.ArrayList;

public class MyArrayListClone {

public static void main(String a[]){


ArrayList<String> arrl = new ArrayList<String>();
//adding elements to the end
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
System.out.println("Actual ArrayList:"+arrl);
ArrayList<String> copy = (ArrayList<String>) arrl.clone();
System.out.println("Cloned ArrayList:"+copy);
}
}

Output:

Actual ArrayList:[First, Second, Third, Random]


Cloned ArrayList:[First, Second, Third, Random]
Program: How to add all elements of a list to ArrayList?

Description:

Here we can see example for copying another collection instance objects to existing ArrayList.

Code:

package com.java2novice.arraylist;

import java.util.ArrayList;
import java.util.List;

public class MyArrayListNewCollection {

public static void main(String a[]){


ArrayList<String> arrl = new ArrayList<String>();
//adding elements to the end
arrl.add("First");
arrl.add("Second");
arrl.add("Third");
arrl.add("Random");
System.out.println("Actual ArrayList:"+arrl);
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
arrl.addAll(list);
System.out.println("After Copy: "+arrl);
}
}

Output:

Actual ArrayList:[First, Second, Third, Random]


After Copy: [First, Second, Third, Random, one, two]
Program: How to delete all elements from my ArrayList?

Description:

Here we can see example for deleting all objects from ArrayList at one method call. We can do this by calling clear() meth
ArrayList, it will delete all objects.

Code:

1 package com.java2novice.arraylist;

3 import java.util.ArrayList;

4
public class ClearMyArrayList {
5

6
public static void main(String a[]){
7
ArrayList<String> arrl = new ArrayList<String>();
8
//adding elements to the end
9
arrl.add("First");
10
arrl.add("Second");
11
arrl.add("Third");
12 arrl.add("Random");

13 System.out.println("Actual ArrayList:"+arrl);

14 arrl.clear();

15 System.out.println("After clear ArrayList:"+arrl);

}
16
}
17
18

Output:

Actual ArrayList:[First, Second, Third, Random]


After clear ArrayList:[]
Program: How to find does ArrayList contains all list elements or not?

Description:

Here we can see example for finding whether the instance of an ArrayList contains all objects of another Collection instanc
checking with another List instance.

Code:

1 package com.java2novice.arraylist;

3 import java.util.ArrayList;

import java.util.List;
4

5
public class MyElementCheck {
6

7
public static void main(String a[]){
8
ArrayList<String> arrl = new ArrayList<String>();
9
arrl.add("First");
10
arrl.add("Second");
11
arrl.add("Third");
12 arrl.add("Random");

13 List<String> list = new ArrayList<String>();


14

15 list.add("Second");

list.add("Random");
16
System.out.println("Does ArrayList contains all list elements?: "
17
+arrl.containsAll(list));
18
list.add("one");
19
System.out.println("Does ArrayList contains all list elements?: "
20
+arrl.containsAll(list));
21 }

22 }

23

Output:

Does ArrayList contains all list elements?: true


Does ArrayList contains all list elements?: false
?
1 package com.java2novice.generics;
2
public class MySimpleGenerics {
3
4 public static void main(String a[]){
5
6 //we are going to create SimpleGeneric object with String as type parameter
7 SimpleGeneric<String> sgs = new SimpleGeneric<String>("JAVA2NOVICE");
8 sgs.printType();
9 //we are going to create SimpleGeneric object with Boolean as type parameter
SimpleGeneric<Boolean> sgb = new SimpleGeneric<Boolean>(Boolean.TRUE);
10 sgb.printType();
11 }
12 }
13
14 /**
15 * Here T is a type parameter, and it will be replaced with
* actual type when the object got created.
16 */
17 class SimpleGeneric<T>{
18
19 //declaration of object type T
20 private T objReff = null;
21
22
23
24 //constructor to accept type parameter T
25 public SimpleGeneric(T param){
26 this.objReff = param;
27 }
28
29 public T getObjReff(){
return this.objReff;
30 }
31
32 //this method prints the holding parameter type
33 public void printType(){
34 System.out.println("Type: "+objReff.getClass().getName());
}
35 }
36
37
38

Output:
Type: java.lang.String
Type: java.lang.Boolean
Program: Write a simple generics class example with two ty
parameters.

Below example shows how to create a simple generics class with two type parameters. Look at the class
defined two types of parameters called U & V, seperated by ",". You can define multiple type parameter
",". Look at sample code for more comments.

package com.java2novice.generics;

public class MySimpleTwoGenerics {

public static void main(String a[]){

SimpleGen<String, Integer> sample


= new SimpleGen<String, Integer>("JAVA2NOVICE", 100);
sample.printTypes();
}
}

/**
* Simple generics class with two type parameters U, V.
*/
class SimpleGen<U, V>{

//type U object reference


private U objUreff;
//type V object reference
private V objVreff;

//constructor to accept object type U and object type V


public SimpleGen(U objU, V objV){
this.objUreff = objU;
this.objVreff = objV;
}

public void printTypes(){


System.out.println("U Type: "+this.objUreff.getClass().getName());
System.out.println("V Type: "+this.objVreff.getClass().getName());
}
}

Output:

U Type: java.lang.String
V Type: java.lang.Integer
Program: How implement bounded types (extend superclass
generics?

As of now we have seen examples for only one type parameter. What happens in case we want to access
objects comes from same family, means extending same super class? You can restrict the generics type p
certain group of objects which extends same super class. You can achieve this my specifying extends <su
class definitions, look at the example, it gives you more comments to understand.

package com.java2novice.generics;
1

2
public class MyBoundedClassEx {
3

4
public static void main(String a[]){
5
//Creating object of sub class C and
6
//passing it to BoundEx as a type parameter.
7
BoundEx<C> bec = new BoundEx<C>(new C());
8 bec.doRunTest();

9 //Creating object of sub class B and

10 //passing it to BoundEx as a type parameter.

11 BoundEx<B> beb = new BoundEx<B>(new B());

beb.doRunTest();
12
//similarly passing super class A
13
BoundEx<A> bea = new BoundEx<A>(new A());
14
bea.doRunTest();
15
//If you uncomment below code it will throw compiler error
16
//becasue we restricted to only of type A and its sub classes.
17
//BoundEx<String> bes = new BoundEx<String>(new String());
class MyClass<T extends TestClass & TestInterface> {

Look at example for more understanding.

1 package com.java2novice.generics;

3 public class MyBoundedInterface {

5 public static void main(String a[]){

7 //Creating object of implementation class X called Y and

8 //passing it to BoundExmp as a type parameter.

BoundExmp<Y> bey = new BoundExmp<Y>(new Y());


9
bey.doRunTest();
10
//Creating object of implementation class X called Z and
11
//passing it to BoundExmp as a type parameter.
12
BoundExmp<Z> bez = new BoundExmp<Z>(new Z());
13
bez.doRunTest();
14
//If you uncomment below code it will throw compiler error
15 //becasue we restricted to only of type X implementation classes.

16 //BoundExmp<String> bes = new BoundExmp<String>(new String());

17 //bea.doRunTest();

18 }

}
19

20
class BoundExmp<T extends X>{
21
Program: What is generics wildcard arguments? Give an exa

Below example exmplains what is wildcard arguments and how it helps us to solve problem. In the exam
two classes called CompAEmp and CompBEmp extending Emp class. We have a generic class called MyEm
where we have utilities to perform employee functions irrespective of which comapany emp belogns too
accepts subclasses of Emp. Incase if we want to compare salaries of two employees, how can we do usin
MyEmployeeUtil class? U can think that below sample code might work, but it wont work.

//this logic wont work


public boolean isSalaryEqual(MyEmployeeUtil<T> otherEmp){

if(emp.getSalary() == otherEmp.getSalary()){
return true;
}
return false;
}

Because once you create an object of MyEmployeeUtil class, the type argument will be specific to an ins
you can compare between only same object types, ie, you can comapare either objects of CompAEmp or
but not between CompAEmp and CompBEmp. To solve this problem, wildcard argument will helps you. L
sample code, which can solve your problem.

public boolean isSalaryEqual(MyEmployeeUtil<?> otherEmp){

if(emp.getSalary() == otherEmp.getSalary()){
return true;
}
return false;
}

So "?" will solve the issue. Look below for complete example.

package com.java2novice.generics;

public class MyWildcardEx {

public static void main(String a[]){


MyEmployeeUtil<CompAEmp> empA
= new MyEmployeeUtil<CompAEmp>(new CompAEmp("Ram", 20000));
MyEmployeeUtil<CompBEmp> empB
= new MyEmployeeUtil<CompBEmp>(new CompBEmp("Krish", 30000))
MyEmployeeUtil<CompAEmp> empC
= new MyEmployeeUtil<CompAEmp>(new CompAEmp("Nagesh", 20000
System.out.println("Is salary same? "+empA.isSalaryEqual(empB));
System.out.println("Is salary same? "+empA.isSalaryEqual(empC));
}
}

class MyEmployeeUtil<T extends Emp>{

private T emp;

public MyEmployeeUtil(T obj){


emp = obj;
}

public int getSalary(){


return emp.getSalary();
}

public boolean isSalaryEqual(MyEmployeeUtil<?> otherEmp){

if(emp.getSalary() == otherEmp.getSalary()){
return true;
}
return false;
}

//// create some utility methods to do employee functionalities


//
//
//
}

class Emp{

private String name;


private int salary;

public Emp(String name, int sal){


this.name = name;
this.salary = sal;
}

public String getName() {


return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}

class CompAEmp extends Emp{

public CompAEmp(String nm, int sal){


super(nm, sal);
}
}

class CompBEmp extends Emp{

public CompBEmp(String nm, int sal){


super(nm, sal);
}
}

Output:

Is salary same? false


Is salary same? true
import java.awt.*;
import javax.swing.*;

/** Simple example illustrating the use of JPanels, especially


* the ability to add Borders.
* 1998-99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
*/

public class JPanels extends JFrame {


public static void main(String[] args) {
new JPanels();
}

public JPanels() {
super("Using JPanels with Borders");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.lightGray);
JPanel controlArea = new JPanel(new GridLayout(3, 1));
String[] colors = { "Red", "Green", "Blue",
"Black", "White", "Gray" };
controlArea.add(new SixChoicePanel("Color", colors));
String[] thicknesses = { "1", "2", "3", "4", "5", "6" };
controlArea.add(new SixChoicePanel("Line Thickness",
thicknesses));
String[] fontSizes = { "10", "12", "14", "18", "24", "36" };
controlArea.add(new SixChoicePanel("Font Size",
fontSizes));
content.add(controlArea, BorderLayout.EAST);
JPanel drawingArea = new JPanel();
// Preferred height is irrelevant, since using WEST region
drawingArea.setPreferredSize(new Dimension(400, 0));
drawingArea.setBorder
(BorderFactory.createLineBorder (Color.blue, 2));
drawingArea.setBackground(Color.white);
content.add(drawingArea, BorderLayout.WEST);
pack();
setVisible(true);
}
}

You might also like