0% found this document useful (0 votes)
13 views12 pages

OOPUnit 6 TotalNote BIT 1684464495521 1708351038647

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views12 pages

OOPUnit 6 TotalNote BIT 1684464495521 1708351038647

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Unit 6: Java Collections

Java collections and generic


Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Generics in Java
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
It makes the code stable by detecting the bugs at compile time.

Before generics, we can store any type of objects in the collection, i.e., non-generic.
Now generics force the java programmer to store a specific type of objects.

1
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow
to store other objects.

2) Type casting is not required: There is no need to typecast the object.

3) Compile-Time Checking: It is checked at compile time so problem will not occur


at runtime. The good programming strategy says it is far better to handle the problem
at compile time than runtime.

Example of Generics in Java


Here, we are using the ArrayList class, but you can use any collection class such as
ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

1. import java.util.*;
2. class TestGenerics1{
3. public static void main(String args[]){

2
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("rahul");
6. list.add("jai");
7. //list.add(32);//compile time error
8.
9. String s=list.get(1);//type casting is not required
10. System.out.println("element is: "+s);
11.
12. Iterator<String> itr=list.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Test it Now

Output:

element is: jai


rahul
jai

Java Collection iterator() Method


The iterator() method of Java Collection Interface returns an iterator over the elements
in this collection.

Syntax

1. public Iterator <E> iterator()

Parameters
NA

Return
The iterator () method returns an iterator over the elements in this collection.

Example 1

3
1. import java.util.Collection;
2. import java.util.Iterator;
3. import java.util.concurrent.ConcurrentLinkedQueue;
4. public class JavaCollectionIteratorExample1 {
5. static int i = 1;
6. public static void main(String[] args) {
7. Collection<String> collection = new ConcurrentLinkedQueue<String>();
8. collection.add("Ram");
9. collection.add("Sham");
10. collection.add("Mira");
11. collection.add("Rajesh");
12. Iterator<String> iterator = collection.iterator();
13. //Returns an iterator over the elements
14. while (iterator.hasNext()) {
15. System.out.println(i++ + "." + iterator.next());
16. }
17. }
18. }
Test it Now

Output:

1.Ram
2.Sham
3.Mira
4.Rajesh

Example 2
1. import java.util.Collection;
2. import java.util.Collections;
3. import java.util.Iterator;
4. import java.util.concurrent.ConcurrentLinkedQueue;
5. public class JavaCollectionIteratorExample2 {
6. public static void main(String[] args) {
7. Integer[] val = new Integer[2];
8. Collection<Integer> collection = new ConcurrentLinkedQueue<Integer>();
9. collection.add(71018);
10. collection.add(8000);
11. collection.add(1178);

4
12. collection.add(1190);
13. //Returns an iterator over the elements
14. Iterator<Integer> iterator = collection.iterator();
15. while(iterator.hasNext()){
16. System.out.println(iterator.next());
17. val[0] = Collections.max(collection);
18. val[1] = Collections.min(collection);
19. }
20. System.out.println("Max number = "+ val[0]);
21. System.out.println("Min number = "+ val[1]);
22. }
23. }
Test it Now

Output:

71018
8000
1178
1190
Max number = 71018
Min number = 1178

Java List
List in Java provides the facility to maintain the ordered collection. It contains the
index-based methods to insert, update, delete and search the elements. It can have
the duplicate elements also. We can also store the null elements in the list.

The List interface is found in the java.util package and inherits the Collection interface.
It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in
forward and backward directions. The implementation classes of List interface
are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are widely used
in Java programming. The Vector class is deprecated since Java 5.

5
Java ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It is like an array,
but there is no size limit. We can add or remove elements anytime. So, it is much more
flexible than the traditional array. It is found in the java.util package. It is like the Vector
in C++.

The ArrayList in Java can have the duplicate elements also. It implements the List
interface so we can use all the methods of the List interface here. The ArrayList
maintains the insertion order internally.

It inherits the AbstractList class and implements List interface.

6
Java LinkedList class

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-
list data structure. It inherits the AbstractList class and implements List and Deque
interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

7
Java HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on
the basis of their hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set


A list can contain duplicate elements whereas Set contains unique elements only.

8
Hierarchy of HashSet class
The HashSet class extends AbstractSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.

Java Map Interface


A map contains values on the basis of key, i.e. key and value pair. Each key and value
pair is known as an entry. A Map contains unique keys.

A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy


There are two interfaces for implementing Map in java: Map and SortedMap, and three
classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given
below:

9
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or
value.

A Map can't be traversed, so you need to convert it into Set


using keySet() or entrySet() method.

TypeSafety/Dart Generics
Dart Generics are the same as the Dart collections, which are used to store the
homogenous data. As we discussed in the Dart features, it is an optionally typed
language.
10
By default, Dart Collections are the heterogeneous type. In other words, a single Dart
collection can hold the values of several data types. However, a Dart collection can be
also stored the homogenous values or same type values.

The Dart Generics provides the facility to enforce a limit on the data type of the values
that can be stored by the collection. These collections can be referred to as the type-
safe collections.

Type safety is a unique feature of the Dart programming, which makes sure that a
memory block can only contain the data of a specific data type.

The generics are a way to support type-safety implementation for all Dart collections.
The pair of the angular bracket is used to declare the type-safe collection. The angular
bracket consists of the data-types of the collection. The syntax is given below.

Syntax -
1. Collection_name <data_type> identifier = new Collection_name<data_type>

We can do the type-safe implementation of various Dart objects such as List, Queue,
Map, and Set. It is also supported by all implementation of the above define collection
types. The syntax is given below.

Example - Generics List


1. void main() {
2. List <String> logStr = new List <String>();
3. logStr.add("CHECK");
4. logStr.add("ERROR");
5. logStr.add("INFO");
6.
7. //iterating across list
8. for (String i in logStr) {
9. print(i);
10. }
11. }

Output

CHECK
ERROR
INFO

11
Explanation:
We created a list that holds the string type-safe and used the add element into it by
using add() function.

If we try to insert the other than the specified value then it will through a compilation
error.

Type wildcards

A wildcard in Java is a useful concept in Java Generics. Wildcards in Java are basically
the question marks which we use in generic programming, it basically represents the
unknown type. We use Java Wildcard widely in situations such as in a type of
parameter, local variable, or field and also as a return type.

There are 3 types of wildcards in Java: Upper bounded wildcards, Lower Bounded
Wildcards, and Unbounded Wildcards.

12

You might also like