0% found this document useful (0 votes)
2 views11 pages

Arraylist.java

The document provides an overview of key Java collections: ArrayList, HashSet, and HashMap. It includes details on creating, modifying, and accessing elements in these collections, along with their characteristics and common operations. Additionally, it highlights differences between arrays and ArrayLists, and lists frequently used methods for each collection type.
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)
2 views11 pages

Arraylist.java

The document provides an overview of key Java collections: ArrayList, HashSet, and HashMap. It includes details on creating, modifying, and accessing elements in these collections, along with their characteristics and common operations. Additionally, it highlights differences between arrays and ArrayLists, and lists frequently used methods for each collection type.
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

Advanced java

ArrayList in Java

ArrayList is a resizable array implementation in Java that is part of the Java Collections Framework.

Package:

import [Link];

Creating an ArrayList

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

Adding Elements

[Link]("Apple");
[Link]("Banana");
[Link]("Orange");

Accessing Elements

[Link]([Link](0)); // Apple

Modifying Elements

[Link](1, "Mango");
[Link](fruits); // [Apple, Mango, Orange]

Removing Elements

[Link]("Orange"); // Remove by value


[Link](0); // Remove by index

Finding Size

[Link]([Link]());

Checking if an Element Exists

[Link]([Link]("Mango")); // true

Iterating Through an ArrayList

Using a for loop:

for (int i = 0; i < [Link](); i++) {


[Link]([Link](i));
}

Using an enhanced for loop:

for (String fruit : fruits) {


[Link](fruit);
}

Complete Example

import [Link];
Advanced java

public class Main {


public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();

[Link]("Apple");
[Link]("Banana");
[Link]("Orange");

[Link]("Fruits: " + fruits);

[Link](1, "Mango");
[Link]("Updated: " + fruits);

[Link]("Orange");
[Link]("After removal: " + fruits);

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

for (String fruit : fruits) {


[Link](fruit);
}
}
}

Count Even Numbers

import [Link];

public class Main {


public static void main(String[] args) {

ArrayList<Integer> nums = new ArrayList<>();

[Link](10);
[Link](15);
[Link](20);
[Link](25);

int count = 0;

for(int n : nums)
{
if(n % 2 == 0)
{
count++;
}
}

[Link](count);
Advanced java

}
}

Array vs ArrayList

Feature Array ArrayList

Size Fixed Dynamic

Stores Primitive & Objects Objects only

Length/Size [Link] [Link]()

Add/Remove Difficult Easy (add(), remove())

Note: ArrayList cannot directly store primitive types like int, double, etc. Use wrapper classes:

ArrayList<Integer> numbers = new ArrayList<>();


[Link](10);
[Link](20);

(Java automatically converts int to Integer using autoboxing.)

Problem 1: Student Names Management

Problem 2: Integer List Operation

Problem 3: Product List Management

HashSet in Java

HashSet is a class in Java that implements the Set interface and stores unique elements. It is backed
by a hash table, which provides fast insertion, deletion, and lookup operations.

Import

import [Link];

Create a HashSet

HashSet<String> fruits = new HashSet<>();

Common Operations

Add elements

[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Apple"); // Duplicate, won't be added

Print elements
Advanced java

[Link](fruits);

Check if an element exists

[Link]([Link]("Banana")); // true

Remove an element

[Link]("Orange");

Get size

[Link]([Link]());

Iterate through HashSet

for (String fruit : fruits) {


[Link](fruit);
}

Example Program

import [Link];

public class Main {


public static void main(String[] args) {
HashSet<Integer> numbers = new HashSet<>();

[Link](10);
[Link](20);
[Link](30);
[Link](10); // Duplicate

[Link]("HashSet: " + numbers);


[Link]("Contains 20? " + [Link](20));

[Link](30);

[Link]("After removal: " + numbers);


[Link]("Size: " + [Link]());
}
}

Key Characteristics

• Stores unique values only.

• Allows one null element.

• Average time complexity for add(), remove(), and contains() is O(1).

Example: Remove duplicates from an array

int[] arr = {1, 2, 2, 3, 4, 4, 5};


Advanced java

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


for (int num : arr) {
[Link](num);
}

[Link](set); // [1, 2, 3, 4, 5]

Problem 1: Unique Student IDs

Problem 2: Unique City Names

Problem 3: Common Subjects

HashMap in Java

HashMap is a class in Java that stores data in key-value pairs.

• Each key is unique.

• A key is used to access its corresponding value.

• It is part of the Java Collections Framework.

• It does not maintain insertion order.

Import

import [Link];

Creating a HashMap

HashMap<Integer, String> students = new HashMap<>();

Here:

• Integer → Key

• String → Value

Common Operations

1. Add Elements (put())

[Link](101, "John");
[Link](102, "Alice");
[Link](103, "Bob");

2. Access Elements (get())

[Link]([Link](102));
Advanced java

Output

Alice

3. Remove Elements (remove())

[Link](103);

4. Check Key Exists (containsKey())

[Link]([Link](101));

Output

true

5. Check Value Exists (containsValue())

[Link]([Link]("Alice"));

Output

true

6. Get Size (size())

[Link]([Link]());

7. Iterate Through HashMap

for (Integer key : [Link]()) {


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

Complete Example

import [Link];

public class HashMapExample {


public static void main(String[] args) {

HashMap<Integer, String> students = new HashMap<>();

[Link](101, "John");
[Link](102, "Alice");
[Link](103, "Bob");
Advanced java

[Link]("Students: " + students);

[Link]("Student 102: " + [Link](102));

[Link](103);

[Link]("After Removal: " + students);

[Link]("Contains Key 101: " + [Link](101));

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


}
}

Output

Students: {101=John, 102=Alice, 103=Bob}


Student 102: Alice
After Removal: {101=John, 102=Alice}
Contains Key 101: true
Size: 2

HashMap Characteristics

Feature HashMap

Stores Key-Value Pairs

Duplicate Keys Allowed

Duplicate Values Allowed

Allows One Null Key

Allows Multiple Null Values

Maintains Order

Sorted

Fast Search O(1) Average

Real-Life Example

Think of a student database:


Advanced java

Roll Number (Key) Name (Value)

101 John

102 Alice

103 Bob

To find a student's name, use the roll number as the key. This is exactly how a HashMap works.

HashMap vs HashSet

Feature HashMap HashSet

Stores Key-Value Pairs Only Values

Duplicate Keys/Values Keys Values Values

Retrieval By Key By Value Search

Example {101=John} [John, Alice]

Problem 1: Student Record System

Problem 2: Employee Salary Management

Problem 3: Product Inventory

ArrayList Methods

Method Description

add(E e) Adds an element to the list

add(int index, E e) Inserts element at a specific index

get(int index) Returns element at the given index

set(int index, E e) Replaces element at the given index

remove(int index) Removes element at the given index

remove(Object o) Removes the specified element

size() Returns the number of elements

contains(Object o) Checks if element exists

isEmpty() Checks if list is empty

clear() Removes all elements

indexOf(Object o) Returns first occurrence index


Advanced java

Method Description

lastIndexOf(Object o) Returns last occurrence index

sort(Comparator c) Sorts the list

toArray() Converts list to array

HashSet Methods

Method Description

add(E e) Adds an element

remove(Object o) Removes an element

contains(Object o) Checks if element exists

size() Returns number of elements

isEmpty() Checks if set is empty

clear() Removes all elements

iterator() Returns an iterator

toArray() Converts set to array

addAll(Collection c) Adds all elements from another collection

removeAll(Collection c) Removes matching elements

retainAll(Collection c) Keeps only matching elements

Note: HashSet does not allow duplicates and does not maintain insertion order.

HashMap Methods

Method Description

put(K key, V value) Adds a key-value pair

get(Object key) Returns value for a key

remove(Object key) Removes a key-value pair

containsKey(Object key) Checks if key exists

containsValue(Object value) Checks if value exists


Advanced java

Method Description

size() Returns number of entries

isEmpty() Checks if map is empty

clear() Removes all entries

keySet() Returns all keys

values() Returns all values

entrySet() Returns all key-value pairs

replace(K key, V value) Replaces value for a key

putIfAbsent(K key, V value) Adds only if key doesn't exist

getOrDefault(K key, V defaultValue) Returns value or default value

Most Frequently Used Methods

ArrayList

add()
get()
set()
remove()
size()
contains()
clear()

HashSet

add()
remove()
contains()
size()
clear()

HashMap

put()
get()
remove()
containsKey()
containsValue()
keySet()
values()
entrySet()
size()
Advanced java

You might also like