0% found this document useful (0 votes)
25 views14 pages

Java Collection Framework Overview

This document discusses different data structures in the Java Collection Framework. It explains key interfaces like List, Set, Queue and their common implementations including ArrayList, LinkedList, Vector, Stack. It compares features of different data structures like capacity, order, duplicates and synchronization.

Uploaded by

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

Java Collection Framework Overview

This document discusses different data structures in the Java Collection Framework. It explains key interfaces like List, Set, Queue and their common implementations including ArrayList, LinkedList, Vector, Stack. It compares features of different data structures like capacity, order, duplicates and synchronization.

Uploaded by

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

COLLECTION FRAMWORK

Collection Framework: Its an api which set of classes and interfaces


Which provides the readymade architecture for data structures like
list, set, queue.
Framework: It is set of classes and interfaces which provides a
readymade architecture.

Iterable: Iterable is a root interface for the entire collection


framework. The collection interface extends the Iterable interface.
Therefore, all the classes and interfaces and classes implements this
interface. the main functionality of this interface is to provide an
iterator for the collection.
Collections: It is utility class .
Collections is a framework provided by java, this framework provides
many interfaces and their implemented classes in order to store a
group of objects in a single entity. All the collections are in
[Link].

Collection : It contains all the basic methods which every collection


has like adding the data into the collection removing the data
creating data ect.
What is the difference between Arrays and Collections?

Arrays Collections

1. They has fixed size [Link] has dynamic size


2. Can store only [Link] store heterogeneous
homogeneous type of data collection of data.
3. Arrays doesn’t support [Link] support generics.
generics 4. Collections have a rich set of
4. Arrays doesn’t have any methods to perform operations
supportive methods to on collections.
perform operations.

1) LIST : List is an interface which provides the facility to store a


group of objects in a single entity, where insertion allowed
based on index, null can be inverted, duplicates are allowed.

List is good: to store and retrieval of data.

List is implemented by 3 classes:


[Link]----> extended by stack
[Link]
[Link]
[Link] :
Vector is a legacy class. It provides a facility to store
a group of objects in a single entity. vector is thread
safe class so suitable for multithreaded environment so
the process of vector will be slow.
class VectorTest
{
static void show()
{
//create
Vector<String> v1 = new Vector<>() ;
[Link]("Pavithra");
[Link]("Sahana");
[Link]("karuna");
[Link]("sapna");
[Link]("madhu");

[Link](v1);

//delete
[Link]("madhu");
[Link](2);

[Link](v1);
[Link]();
[Link](v1);

[Link]([Link]());//10

[Link]([Link]()); //3--no of
elements present

Vector<Object> v2= new Vector<>();


[Link]("kavya");
[Link]("preeti");
[Link]("sandhya");

[Link](v1); //if genetics applied to v2 this


will not be allowed
[Link](v2);
[Link](2,v1);
[Link]([Link](v1)); // stores all
the elements of v1 as an single object
[Link](v2);

//Retrieve
[Link]([Link](3));

//remove duplicate elements


Vector<String> v3 = new Vector<>();

[Link]("kavya");
[Link]("preeti");
[Link]("sandhya");
/*for(Object st : v2)
{
if([Link](st)==false)
{
[Link]((String) st);
}
}*/
[Link]("sahana");
[Link](0, "pratibha");
[Link](0, "karunya");

[Link](v2);

int a[]= {2,3,4,1,8};


Vector< Integer> obj = new
Vector([Link](a)); //converting array to list

//conver arrayList to array

Object a2[] = [Link]();

}
}
public class VectorsDemo {

public static void main(String[] args) {

[Link]();
}

[Link]: Array list provides a facility to store a group


of objects in a single entity. And the object of an
arraylist supports duplicate elements & stores elements
based on index
And insertion order.

Array list is best for store and retrieval of elements.

Ex : public class ArrayListDemo {

public static void main(String[] args) {

//add

ArrayList<String> obj = new ArrayList<>();


[Link]("rama");
[Link]("suma");
[Link](0,"vanitha");
[Link]("sadana");
[Link](obj);

[Link](3);
//retrieve
[Link]([Link](1));

[Link]([Link]("sadana"));
Verify

[Link]([Link](1, "madhu"));
//update
[Link](obj);
What is the difference between Array list and vector?

Vector Array List


[Link] is a legacy class [Link] is not a legacy class
implements list interface. but implements list interface.

[Link] is a thread safe multiple [Link] is not a thread safe


threads cannot be handled multiple threads can be handled
simultaneously, so it is a simultaneously, so it is not
synchronized one by default. synchronized one by default.
[Link] is more efficient than
[Link] vector performance is slow vector.
[Link] grows doubling its [Link] grows 50% of its current
current size, so it is suitable for size, so it is more efficient for
where huge amount of data memory usage.
increases exponentially.

[Link] : Stack is a class which extends vector class and list


interface and provides a facility to store a group of objects as a single
entity. It represents the last in first out (LIFO) principle.
Suitable for – redo, undo, last saved transactions, browser history.
special methods availabale in stacks
 push () – adds an element at top of the list
 pop () -- removes the top most element
 peek () – shows top most element
 search () – finds the element.
 IndexOf () --

public class StacksDemo {

public static void main(String[] args) {

Stack<String> book = new Stack<>();


[Link]("java"); //add to stack
[Link]("c++");
[Link]("c");
[Link]("networks");
[Link]("c#");

[Link](); //remove top element

[Link](); //view top most element

[Link](0); //remove element based on index

[Link]("card");
[Link]([Link]("c"));

[Link]([Link]("c"));

Linked list: linked list extends list and dequeuer interfaces


Linked list allows to store a group of objects in a single entity.
internally it stores in the form of nodes, each node contains the
address of previous node, item and address of the next node.
It allows duplicates and follows insertion order, null can be accepted.
Linked list doesn’t create memory until inserting an element .
It is best for data manipulating i.e. add or delete element from
linked list, because there is no shifting operation takes place.
package [Link];

import [Link];

public class LinkeListDemo {

public static void main(String[] args) {

LinkedList<String> l = new LinkedList<>();


[Link]("sindhu"); //add elements
[Link]("pavan");
[Link]("navya");
[Link]("balu");
[Link]("abhi");
[Link]("tanu");

[Link]("abhi"); //remove element

[Link](); // remove elements -- first and last node

//makes null so that all the elements goes into garbage


collection

[Link]("pavan"); //verify

[Link](0,"sainath") // update

[Link]([Link](0));
}
Vector ArrayLi Stack Linked Priorit ArrayD Hash Linked Tree
st s List yQ Q set hashs set
et
Default cap?
10 0 10 0 11 17 0 16 0
Initial cap?
10 10 10 0 11 17 16 16 0
Duplicate
element?
Yes Yes Yes Yes Yes Yes No No No
Allow null
Value?
Yes Yes Yes Yes No No Yes Yes No
Maintains
insertion Yes Yes Yes Yes Yes No No Yes No
order?
Sorted
order?
No No No No No No No No Yes
Random No
access? Yes Yes Yes Yes No No No No
Synchronize Yes(
d? but
we
No No No No
Yes No shou Yes no
ld
not
use)
What is Best Uses
good for? Uses
for Data tree
Multithr data
hash
manup map
eading, manu Heigh ulation map
To Uses and
Best for pulati priori can be to
store linke follo
when on like stor
and ty done d ws
data is LIFO add, e
retreiv remov first from hash bina
exponen data
e e. Bcz out both map , ry
tially inter
no the stru
growing shiftin
nally
sides. ctur
g .
e.
Queue: Queue is an interface which extends list interface. And
allows to store a group of data as a single entity First in First out
principle (FIFO). here duplicates are allowed but not null, and
random access of elements is not allowed.
Mainly categorized into 2 types
a. Priority queue.
b. Arraydequeue

a. Priority queue: It is a class implements queue interface. It


works based on the higher priority first out principle(HPFO).
Here duplicates are allowed and null is not inverted, it maintains
the insertion order, random access cannot be done.
Applicable in hospital queue, ticket reservation system.
Methods:
Peek (): shows the head element (head element means higher
prioritized element)
Poll (): we can remove the head element.

b. Arraydequeue: It is a special kind of queue that allows to do


data manipulation from both the sides that is adding or
removing.
Suitable for where efficient insertion and deletion is done.
Supportive methods are
Addition: offerFirst(), offerLast(), addFirst(), addLast().
Retrieve: peek(), peekFirst(), peekLast().
Removal: poll(), pllFirst(), pollLast().
Set: set is an interface which extends the collection interface.
And it allows to store only a unique set of data. Set internally
implements map.

Hash set: the object of hashmap stores the elements randomly in


memory using hash map (array of nodes(key and value pair)). If we
do not provide any value by default it creates a dummy object of
object and doesn’t allow duplicates.
Note: updation cannot be allowed here.

Linked Hash set:

Tree set: tree set internally uses tree map binary structure to store
the elements. The object of tree set stores the elements based on
sorted assending order.
Note: at any point the object of tree set never support without
approach of generics object creation.
TreeSet<Integer> t = new TreeSet<>();
[Link](12);
[Link](10);
[Link](20);
[Link](13);
[Link](9);
[Link](t); // [9, 10, 12, 13, 20]

[Link]([Link]()); //returns first/


highest element

[Link]([Link]()); //returns last/


lowest element

[Link]([Link]()); // removes
first element

[Link]([Link]()); // removes last


element

[Link]([Link](12, 20)); // returns


elements between 12 to 20

//creates a virtual set . operations performed on


subset reflects on main set.

[Link]([Link](12,20).removeAll(t));
// removes between 12 to 20 in main set

MAP : map is an interface, it provides a facility to store a group


of objects as a single entity in the form of key and value pair. Here
key always must be unique one.
When we prefer map ?
List is not applicable for huge amount of data because it is difficult to
remember all the ids and also list iterates every time so its
performance will be slow. In order to overcome this we prefer map .
There are 2 main maps
a. Hash map
b. Tree map

a. Hash map: Object of hash map supports key and value pair of
adding elements. Here key should be unique, it stores keys in the
memory randomly.

Map<Integer, String> m = new Hashtable<>();


[Link](1, "bengaluru"); //adding elements
[Link](2,"chennai");
[Link](3, "hydrabad");
[Link](4, "delhi");
[Link](5, "delhi");
[Link](m);
[Link]([Link]()); // returns only
the keys

[Link]([Link]()); // returns only


values

//iterate keys

Set<Integer> key = [Link]();


for(Integer k:key)
{
[Link](k);
}

//iterate values

Collection<String> value = [Link]();


for(String v : value)
{
[Link](v);
}

//get value based on key

[Link]([Link](4));

for(Integer k:key)
{
[Link](k+ " ==> "+[Link](k));
}

//remove element

[Link]([Link](4));

//verification

[Link]([Link](4)); //returns
boolean value

[Link]([Link]("delhi"));
Treemap :

Common questions

Powered by AI

LinkedList and ArrayDeque both support data manipulation, but they are optimized for different scenarios. LinkedList, which implements List and Deque interfaces, allows efficient insertions and deletions due to its node-based structure, making it suitable for frequent addition or removal of elements . It maintains insertion order, allows duplicates, and provides operations like add, remove, and clear . On the other hand, ArrayDeque supports efficient insertion and deletion from both ends, which makes it ideal for queue functionalities where such operations are common . ArrayDeque does not allow null elements and performs better than LinkedList when used as a simple queue or double-ended queue, providing specific methods such as offerFirst(), offerLast(), pollFirst(), and pollLast() for tailored deque operations .

You would choose to use a Stack in scenarios requiring a Last In First Out (LIFO) order, such as implementing features for undo and redo operations, navigating backward in browser history, or handling nested function calls . The Stack class, which extends the Vector class and implements the List interface, provides methods like push(), pop(), peek(), and search(), which facilitate managing elements in a LIFO manner . This makes it suitable for tasks where such backward navigation or reversal of recent actions is pivotal . Compared to other collections, Stack is designed specifically for these use cases, offering inherent LIFO operations not directly available in more general-purpose collection classes like ArrayList or LinkedList .

TreeSet and HashSet in Java handle elements differently due to their underlying structures. A TreeSet is backed by a TreeMap and maintains its elements in sorted order, achieving this through a binary search tree structure, which ensures that operations like add, remove, and search are performed in O(log n) time complexity . This makes TreeSet suitable for scenarios where sorted set operations are required . Conversely, a HashSet is backed by a HashMap and stores elements in a hash table, allowing for constant-time performance for basic operations (add, remove, contains) assuming the hash function disperses the elements properly across the hash table . However, it does not maintain any order of elements. Consequently, HashSet is more appropriate for cases where the uniqueness of elements is critical but order of elements can be arbitrary .

Vectors and ArrayLists handle memory allocation differently, affecting their performance and usage. A Vector grows by doubling its array size, leading to potentially more significant memory overhead for systems dealing with large data, but this also avoids frequent resizing operations . This strategy can be advantageous in applications where data size increases rapidly and unpredictably . In contrast, an ArrayList increases its array size by 50% when it needs more space, which helps avoid the higher memory overhead associated with the aggressive growth strategy of Vectors . This makes ArrayLists easier on memory but involves more frequent resizing operations compared to Vectors. Thus, ArrayLists are more efficient in terms of memory management and are preferred when performance (speed) outweighs the benefit of fewer resizes .

ArrayList and Vector are both implementations of the List interface in Java, but they differ significantly in terms of performance and usage. Vector is a legacy class that implements the List interface and is synchronized, meaning it is thread-safe but tends to be slower due to the overhead of synchronization . It grows by doubling its current size, which is useful when data increases exponentially . In contrast, ArrayList is not synchronized, allowing multiple threads to access it simultaneously, making it more efficient than Vector for most applications . ArrayList increases its size by 50% of its current capacity when needed, making it more efficient in memory usage compared to the aggressive growth strategy of Vector .

Implementing the Iterable interface makes the Java Collection Framework more versatile and user-friendly by providing a common interface for all collection classes to enable iteration over collections of objects with the enhanced for-loop . This standardized approach simplifies the process of traversing elements in a collection, regardless of the specific type of collection, and enriches code readability and maintainability . Moreover, by implementing Iterable, collection classes can be passed to methods expecting iterable types, offering greater flexibility and reusability of code. The Iterable interface also lays down a foundation for supporting advanced operations, like filtering and transformation, using Java Streams and the forEach method, which further enhances the capabilities and usability of collections for developers .

The Collection Framework in Java differs from the concept of Arrays in several ways. Arrays in Java have a fixed size, can only store homogeneous data, do not support generics, and lack supportive methods for operations . In contrast, the Collection Framework offers a dynamic size, supports heterogenous data storage, supports generics, and provides a rich set of methods for performing operations . The major advantage of the Collection Framework over Arrays is its flexibility and scalability; Collections can dynamically adjust their size and provide more efficient data management capabilities through APIs, which are not possible with Arrays due to their static nature .

A PriorityQueue in Java is a data structure that implements a queue where each element has a priority, and elements are dequeued in order of their priority rather than in the strict order they were enqueued . The PriorityQueue does not allow null and does not maintain insertion order; instead, it orders elements according to their natural ordering or by a comparator provided at queue construction time . It is typically used in scenarios such as algorithmic problem-solving that involves minimum spanning trees or Dijkstra's shortest path algorithm, job scheduling systems, and any situation requiring high-priority tasks to be executed before low-priority tasks .

A developer might choose LinkedHashSet over other Set implementations when insertion order maintenance is required alongside most operations' average constant time performance . LinkedHashSet provides the uniqueness constraints of a Set while allowing predictable iteration order based on the elements' insertion order, which is not the case with HashSet that employs a hash table not preserving order . Compared to TreeSet, which provides sorted order based on natural order or comparator, LinkedHashSet offers the order-preserving advantage without the overhead of maintaining tree structures, which results in faster performance when sorting is not needed . This makes LinkedHashSet beneficial in applications like cache implementations or scenarios where result order is crucial .

HashMap and TreeMap both offer key-value pair storage but differ significantly in how they manage data. HashMap stores entries in a hash table, providing constant-time performance for most operations like add, remove, and access, assuming a good hash function. This makes it ideal for scenarios where speed is critical and key uniqueness is valuable, but without any guaranteed ordering of entries . On the other hand, TreeMap maintains entries in a sorted order based on either the natural order of keys or a specified comparator, using a red-black tree structure. This supports operations such as headMap, tailMap, and subMap, and offers log(n) time complexity for insertion, deletion, and access . This sorted order comes at a cost of slower performance compared to hash-based structures but is beneficial when ordered operations and data traversal in sorted order are necessary . TreeMap is thus more advantageous in applications demanding sorted key management, while HashMap is preferable when performance and unordered access are more important .

You might also like