0% found this document useful (0 votes)
3 views23 pages

Collection Interface in Java

The Collection interface in Java is a fundamental part of the Java Collections Framework, providing methods for adding, removing, and iterating over elements. It serves as a base for various interfaces like List, Set, and Queue, each with specific characteristics and implementations. Additionally, it includes legacy classes such as Vector and Hashtable, which are less commonly used in modern applications due to performance and flexibility issues.

Uploaded by

subathankaraj
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)
3 views23 pages

Collection Interface in Java

The Collection interface in Java is a fundamental part of the Java Collections Framework, providing methods for adding, removing, and iterating over elements. It serves as a base for various interfaces like List, Set, and Queue, each with specific characteristics and implementations. Additionally, it includes legacy classes such as Vector and Hashtable, which are less commonly used in modern applications due to performance and flexibility issues.

Uploaded by

subathankaraj
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 Interface in Java

The Collection interface is a root interface of the Java Collections Framework. It represents a group of
objects (called elements) and provides basic operations like adding, removing, and iterating elements.

📦 Package: `[Link]`

Hierarchy of Collection Interface

Iterable

Collection

↑ ↑ ↑

List Set Queue

`Map` is not part of the Collection interface.

What does Collection interface do?

It defines common methods that all collection classes must implement, such as:

Add elements

Remove elements

Search elements

Iterate elements

Important Methods of Collection Interface

Method Description

add(E e) Adds an element

`addAll(Collection c)` Adds all elements

`remove(Object o)` Removes an element

`removeAll(Collection c)` Removes all elements

`retainAll(Collection c)` Keeps common elements

`size()` Returns number of elements


isEmpty() Checks if empty

contains(Object o) Checks element presence

iterator() Returns iterator

clear() Removes all elements

toArray() Converts to array

Interfaces that extend Collection

1. List Interface

Allows duplicate elements

Maintains insertion order

Example classes:

ArrayList, LinkedList. ,Vector

Example:

Major Collection Classes

1. ArrayList

Uses dynamic array

Allows duplicate elements

Maintains insertion order

Fast random access

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

[Link]("A");

[Link]("B");

2. LinkedList

Uses doubly linked list

Allows duplicates
Better for frequent insertion/deletion

LinkedList<Integer> ll = new LinkedList<>();

[Link](10);

[Link](20);

3. Vector

Same as ArrayList but synchronized

Slower due to thread safety

Legacy class

java

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

[Link]("Java");

4. Stack

Follows LIFO (Last In First Out)

Subclass of Vector

java

Stack<Integer> s = new Stack<>();

[Link](10);

[Link](20);

2. Set Interface

No duplicate elements

Does not maintain insertion order (except `LinkedHashSet`)

Example classes:
`HashSet

LinkedHashSet

TreeSet

Example:

java

Set<Integer> set = new HashSet<>();

[Link](10);

[Link](10); // ignored

3. Queue Interface

Follows FIFO (First In First Out)

Example classes:

PriorityQueue

ArrayDeque

Example:

java

Queue<Integer> q = new LinkedList<>();

[Link](10);

[Link](20);

Why Collection Interface is Important

✔ Provides standard methods

✔ Ensures code reusability

✔ Supports polymorphism

✔ Easy to switch implementations (`ArrayList` → `LinkedList`)

Simple Example Using Collection

java
Collection<String> c = new ArrayList<>();

[Link]("Java");

[Link]("Python");

[Link]("C++");

for(String s : c) {

[Link](s);

Collection vs Collections

Collection Collections

Interface Utility class

Represents group of objects Provides static methods

add() ,remove(),sort(), reverse()

Collection Classes in Java

The Java Collection classes are the implementations of the Collection interfaces provided in the
`[Link]` package. These classes store, manipulate, and retrieve groups of objects.

Hierarchy of Collection Classes

Collection (Interface)

List

ArrayList

LinkedList

Vector

Stack

Set

HashSet

LinkedHashSet

TreeSet
Queue

PriorityQueue

ArrayDeque

Map is not a Collection, but part of the Collections Framework.

[Link]();

Set Classes

5. HashSet

No duplicates

No insertion order

Fast performanc

java

HashSet<Integer> hs = new HashSet<>();

[Link](10);

[Link](10); // ignored

6. LinkedHashSet

Maintains insertion order

No duplicates

java

LinkedHashSet<Integer> lhs = new LinkedHashSet<>();

7. TreeSet

Stores elements in sorted order

No duplicates

java

TreeSet<Integer> ts = new TreeSet<>();

Queue Classes
8. PriorityQueue

Elements processed by priority

Not FIFO

`java

PriorityQueue<Integer> pq = new PriorityQueue<>();

9. ArrayDeque

Faster than Stack & LinkedList

Can be used as queue or stack

`java

ArrayDeque<Integer> ad = new ArrayDeque<>();

Map Classes (Not Collection)

Class Description

HashMap Key-value pairs, no order

LinkedHashMap Maintains insertion order

TreeMap Sorted by key

Hashtable Synchronized (legacy)

Quick Comparison Table

Class Duplicate Order Thread-safe

ArrayList Yes Yes No

LinkedList Yes Yes No

Vector Yes Yes Yes

HashSet No No No

LinkedHashSet No Yes No

TreeSet No Sorted No

Enumeration in Java
In Java, Enumeration is a legacy interface used to traverse (iterate) elements of a collection, mainly in
older classes like Vector and Hashtable.

1. What is Enumeration?

Part of [Link] package

Used to retrieve elements one by one

Introduced in Java 1.0

It works only with legacy classes

2. Enumeration Interface Methods

Method Description

boolean hasMoreElements() Checks if more elements are present

E nextElement() Returns the next element

3. Example of Enumeration

java

import [Link].;

class EnumerationExample {

public static void main(String[] args) {

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

[Link]("Java");

[Link]("Python");

[Link]("C++");

Enumeration<String> e = [Link]();

while ([Link]()) {

[Link]([Link]());

}
outtput

Java

Python

C++

Enumeration with Hashtable

java

import [Link].;

class EnumHash {

public static void main(String[] args) {

Hashtable<Integer, String> ht = new Hashtable<>();

[Link](1, "Apple");

[Link](2, "Banana");

Enumeration<Integer> keys = [Link]();

while ([Link]()) {

int key = [Link]();

[Link](key + " = " + [Link](key));

5. Enumeration vs Iterator

Enumeration Iterator

Legacy interface Modern interface

Read-only Can remove elements

Works with Vector, Hashtable Works with all collections

Not fail-fast Fail-fast


6. Limitations of Enumeration

Cannot remove elements

Works only with legacy classes

Replaced by Iterator and ListIterator

7. When to Use Enumeration?

Only when working with old legacy code

Otherwise, use Iterator or for-each l

Legacy Classes in Java

Legacy classes are old classes that were introduced in early versions of Java (Java 1.0), before the
Collection Framework (Java 1.2). They are still available for backward compatibility, but are rarely used
in new programs.

1. List of Legacy Classes

| Legacy Class | Package |

| ------------- | ----------- |

| `Vector` | `[Link]` |

| `Stack` | `[Link]` |

| `Hashtable` | `[Link]` |

| `Enumeration` | `[Link]` |

2. Why Are They Called Legacy?

Introduced before Collection Framework

Not fully compatible with modern collections

Mostly synchronized (thread-safe by default)

Slower performance

Replaced by newer classes

3. Examples of Legacy Classes

Vector Example
java

Vector<Integer> v = new Vector<>();

[Link](10);

[Link](20);

Stack Example

`java

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

[Link]("A");

[Link]("B");

[Link]([Link]());

Hashtable Example

`java

Hashtable<Integer, String> ht = new Hashtable<>();

[Link](1, "Java");

[Link](2, "Python");

Legacy vs Modern Collection Classes

| Legacy | Modern |

| ------------- | ---------------------- |

| `Vector` | `ArrayList` |

| `Stack` | `Deque` / `ArrayDeque` |

| `Hashtable` | `HashMap` |

| `Enumeration` | `Iterator` |

5. Disadvantages of Legacy Classes

* Poor performance due to synchronization

* Limited methods
* Not flexible

* Not recommended for new applications

6. When Should You Use Legacy Classes?

Maintaining old Java applications

Vector in Java

Vector is a legacy class in Java used to store objects in a dynamic array. It is part of the `[Link]`
package and is synchronized by default.

1. What is Vector?

* Introduced in Java 1.0

* Legacy class

* Implements List interface

* Allows duplicate elements

* Maintains insertion order

* Thread-safe (synchronized)

---

## 2. Class Hierarchy

Object

AbstractCollection

AbstractList

Vector

3. Key Features of Vector


| Feature | Description |

| ------------ | ------------------------------- |

| Dynamic size | Grows and shrinks automatically |

| Synchronized | Thread-safe |

| Index-based | Supports random access |

| Legacy | Uses Enumeration |

## 4. Creating a Vector

Vector<Integer> v = new Vector<>();

## 5. Common Methods

| Method | Use |

| ------------------- | ------------------- |

| `add(E e)` | Add element |

| `addElement(E e)` | Legacy add method |

| `get(int index)` | Get element |

| `remove(int index)` | Remove element |

| `size()` | Number of elements |

| `capacity()` | Total capacity |

| `elements()` | Returns Enumeration |

6. Example Program

java

import [Link].*;

class VectorExample {

public static void main(String[] args) {


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

[Link]("Java");

[Link]("Python");

[Link]("C++");

Enumeration<String> e = [Link]();

while ([Link]()) {

[Link]([Link]());

Output

Java

Python

c++

7. Capacity of Vector

* Default capacity = 10

* When full → capacity doubles

java

Vector<Integer> v = new Vector<>(5);

[Link]([Link]()); // 5

8. Vector vs ArrayList
| Vector | ArrayList |

| --------------------- | ------------------ |

| Synchronized | Not synchronized |

| Slower | Faster |

| Legacy | Modern |

| Enumeration supported | Iterator supported |

9. When to Use Vector?

✔ Multithreaded environment (rare case)

❌ New applications (prefer `ArrayList`)

Stack in Java

Stack is a legacy class in Java used to store elements in LIFO order

(Last In, First Out). It belongs to the `[Link]` package and extends the `Vector` class.

1. What is Stack?

Introduced in Java 1.0

Legacy class

Extends Vector

* Synchronized (thread-safe)

* Follows LIFO principle

- 2. Stack Class Hierarchy

bject

AbstractCollection

AbstractList
|

Vector

Stack

3. Stack Operations (LIFO)

| Operation | Method |

| ----------- | ------------------ |

| Push | `push(E item)` |

| Pop | `pop()` |

| Peek | `peek()` |

| Search | `search(Object o)` |

| Empty check | `empty()` |

4. Example Program

java

import [Link];

class StackExample {

public static void main(String[] args) {

Stack<Integer> s = new Stack<>();

[Link](10);

[Link](20);

[Link](30);

[Link]("Top element: " + [Link]());

[Link]("Removed: " + [Link]());


[Link]("Stack: " + s);

Output

Top element: 30

Removed: 30

Stack: [10, 20]

5. Important Methods Explained

`push()`

Adds element to top of stack.

`pop()`

Removes and returns top element.

⚠ Throws `EmptyStackException` if stack is empty.

`peek()`

Returns top element without removing it.

`search()`

Returns 1-based position from top of stack.

---

6. Stack vs ArrayDeque (Modern Alternative)

| Stack | ArrayDeque |

| --------------------- | ---------------- |

| Legacy class | Modern |

| Slower (synchronized) | Faster |


| Extends Vector | Implements Deque |

| Not recommended | Recommended |

7. When Should You Use Stack?

✔ For understanding LIFO concept

❌ Not recommended for new applications

Use ArrayDeque instead.

stack is a legacy class that extends Vector and follows LIFO

Hashtable in Java

Hashtable is a legacy class in Java used to store data in key–value pairs.

It belongs to the `[Link]` package and is synchronized by default.

1. What is Hashtable?

* Introduced in Java 1.0

* Legacy class

* Stores key–value pairs

* Thread-safe (synchronized)

* Does not allow null key or null value

2. Class Hierarchy

Object

AbstractMap

Hashtable

3. Key Features of Hashtable

| Feature | Description |
| ------------------- | ---------------- |

| Key–Value storage | Similar to Map |

| Synchronized | Thread-safe |

| No null key/value | Both not allowed |

| Legacy | Old class |

| Enumeration support | Yes |

4. Creating a Hashtable

```java

Hashtable<Integer, String> ht = new Hashtable<>();

5. Common Methods

| Method | Purpose |

| ----------------------------- | ----------------------------- |

| `put(K,V)` | Insert element |

| `get(Object key)` | Retrieve value |

| `remove(Object key)` | Delete entry |

| `containsKey(Object key)` | Check key |

| `containsValue(Object value)` | Check value |

| `keys()` | Returns Enumeration of keys |

| `elements()` | Returns Enumeration of values |

6. Example Program

``java

import [Link].*;

class HashtableExample {

public static void main(String[] args) {

Hashtable<Integer, String> ht = new Hashtable<>();


[Link](1, "Java");

[Link](2, "Python");

[Link](3, "C++");

Enumeration<Integer> keys = [Link]();

while ([Link]()) {

int key = [Link]();

[Link](key + " : " + [Link](key));

Output

1 : Java

2 : Python

3 : C++

7. Hashtable vs HashMap

| Hashtable | HashMap |

| ----------------- | ------------------------------------------ |

| Synchronized | Not synchronized |

| Slower | Faster |

| No null key/value | Allows one null key & multiple null values |

| Legacy | Modern |

8. When to Use Hashtable?

Old legacy applications

Thread-safe map without extra synchronization

❌ New projects (use `HashMap` or `ConcurrentHashMap`)


9. Exam Tip

> Hashtable does not allow null key or null value and is synchronized.

### String Class in Java

The String class in Java is used to create and manipulate text (sequence of characters).

It belongs to the `[Link]` package and is immutable.

1. What is String?

Represents a sequence of characters

* Immutable (cannot be changed once created)

* Automatically imported (`[Link]`)

* Supports String pool (memory optimization)

2. Creating String Objects

1️⃣ Using String Literal

java

String s1 = "Java";

Stored in String Constant Pool

Memory efficient

Using `new` Keyword

`java

String s2 = new String("Java");

* Stored in Heap memory

* Creates new object every time

3. Immutability of String

`java

String s = "Hello";

s = [Link](" World");
[Link](s);

✔ A new object is created

❌ Original string is not modified

4. Common String Methods

| Method | Description |

| -------------------- | ------------------ |

| `length()` | Returns length |

| `charAt(int)` | Returns character |

| `concat(String)` | Joins strings |

| `equals(Object)` | Content comparison |

| `equalsIgnoreCase()` | Case-insensitive |

| `toUpperCase()` | Convert to upper |

| `toLowerCase()` | Convert to lower |

| `substring()` | Extract part |

| `trim()` | Remove spaces |

| `replace()` | Replace characters |

5. String Comparison

```java

String a = "Java";

String b = "Java";

[Link](a == b); // true (same pool)

[Link]([Link](b)); // true (same content)

6. String Pool (Important)

Stores string literals

Avoids duplicate objects


* Improves memory usage

```java

String x = "Hello";

String y = "Hello"; // both refer to same object

7. String vs StringBuffer vs StringBuilder

| Feature | String | StringBuffer | StringBuilder |

| ----------- | --------- | ------------ | ------------- |

| Mutability | Immutable | Mutable | Mutable |

| Thread-safe | Yes | Yes | No |

| Performance | Slow | Medium | Fast |

8. When to Use String?

✔ When text does not change frequently

✔ For constants and literals

. Exam Tip

String is immutable and stored in String Constant Pool.

You might also like