Java Topic
Java Collections
The Java Collection is a unified architecture for representing and manipulating collections. It provides interfaces, implementations, and algorithms to work with groups of objects.
Collection Interface Hierarchy
Iterable (Interface) -> Collection (Interface) -> List, Set, Queue (Interfaces) -> Various Implementations
1. Overview of Core Interfaces
The core interfaces in the Java Collections Framework include:
List: An ordered collection (also known as a sequence) that allows duplicate elements. Examples includeArrayListandLinkedList.Set: A collection that does not allow duplicate elements. Examples includeHashSetandTreeSet.Queue: A collection designed for holding elements prior to processing. Examples includeLinkedList(used as a queue) andPriorityQueue.Map: An object that maps keys to values, with no duplicate keys allowed. Examples includeHashMapandTreeMap.
2. List Interface
The List interface represents an ordered collection, where elements can be accessed by their position (index) in the list. It also allows duplicate elements.
Java ArrayList
ArrayList is a part of the java.util package and is a resizable array implementation of the List interface. It allows for dynamic resizing and provides methods for manipulating the size of the array that is used internally to store the list.
1. Creating an ArrayList
To use an ArrayList, you need to import it from the java.util package and then instantiate it:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println(list);
}
}
This example creates an ArrayList of String and adds three elements to it.
2. Accessing Elements
You can access elements in an ArrayList using the get() method:
public class AccessElementsExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
String fruit = list.get(1);
System.out.println("Element at index 1: " + fruit);
}
}
This example retrieves the element at index 1 and prints it out.
3. Removing Elements
You can remove elements from an ArrayList using the remove() method:
public class RemoveElementsExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("Before removal: " + list);
list.remove("Banana");
System.out.println("After removal: " + list);
}
}
This example demonstrates removing an element by its value.
4. Iterating Over Elements
You can iterate over the elements in an ArrayList using a for loop, an enhanced for loop, or an Iterator:
import java.util.ArrayList;
import java.util.Iterator;
public class IterateExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("Using for loop:");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("Using enhanced for loop:");
for (String fruit : list) {
System.out.println(fruit);
}
System.out.println("Using iterator:");
Iterator< String > iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
This example demonstrates three different ways to iterate over an ArrayList.
5. Common Methods
Here are some commonly used methods of the ArrayList class:
add(E e): Adds an element to the end of the list.remove(Object o): Removes the first occurrence of the specified element.get(int index): Returns the element at the specified position in the list.size(): Returns the number of elements in the list.clear(): Removes all elements from the list.
public class CommonMethodsExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("List size: " + list.size());
list.remove("Banana");
System.out.println("List after removal: " + list);
list.clear();
System.out.println("List after clearing: " + list);
}
}
This example demonstrates how to use some common methods of the ArrayList class.
Java List
The List interface is part of the java.util package and represents an ordered collection of elements. It allows duplicate elements and provides positional access and insertion.
1. Implementations of List
Common implementations of the List interface include:
ArrayList: Resizable-array implementation of theListinterface.LinkedList: Doubly-linked list implementation of theListinterface.Vector: Synchronized resizable-array implementation of theListinterface.
2. Basic Operations
Here are some basic operations you can perform with a List:
Creating a List
import java.util.ArrayList;
public class ListCreationExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println(list);
}
}
This example demonstrates how to create an ArrayList as a List and add elements to it.
Accessing Elements
import java.util.List;
import java.util.ArrayList;
public class AccessElementsExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
String fruit = list.get(1);
System.out.println("Element at index 1: " + fruit);
}
}
In this example, we use get() to retrieve an element at a specific index.
Removing Elements
import java.util.List;
import java.util.ArrayList;
public class RemoveElementsExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("Before removal: " + list);
list.remove("Banana");
System.out.println("After removal: " + list);
}
}
Here, we demonstrate how to remove an element by its value.
Iterating Over a List
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class IterateListExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("Using for loop:");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("Using enhanced for loop:");
for (String fruit : list) {
System.out.println(fruit);
}
System.out.println("Using iterator:");
Iterator< String > iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
This example illustrates three ways to iterate over a List.
3. Common Methods
Here are some commonly used methods of the List interface:
add(E e): Adds an element to the list.remove(Object o): Removes the first occurrence of the specified element.get(int index): Returns the element at the specified position in the list.size(): Returns the number of elements in the list.clear(): Removes all elements from the list.
public class CommonListMethodsExample {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("List size: " + list.size());
list.remove("Banana");
System.out.println("List after removal: " + list);
list.clear();
System.out.println("List after clearing: " + list);
}
}
This example demonstrates some common methods used with a List.
Java LinkedList
The LinkedList class is a part of the java.util package and implements the List and Deque interfaces. It represents a doubly-linked list, which allows for efficient insertion and removal of elements from both ends of the list.
1. Creating a LinkedList
To use a LinkedList, you need to import it from the java.util package and then instantiate it:
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println(list);
}
}
This example creates a LinkedList of String and adds three elements to it.
2. Accessing Elements
You can access elements in a LinkedList using the get() method:
import java.util.LinkedList;
public class AccessLinkedListElements {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
String fruit = list.get(1);
System.out.println("Element at index 1: " + fruit);
}
}
This example retrieves the element at index 1 and prints it out.
3. Adding and Removing Elements
You can add elements to specific positions and remove elements from a LinkedList:
import java.util.LinkedList;
public class ModifyLinkedList {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("Original List: " + list);
list.addFirst("Strawberry");
list.addLast("Blueberry");
list.remove("Banana");
System.out.println("Modified List: " + list);
}
}
This example demonstrates adding elements to the beginning and end of the list and removing an element.
4. Iterating Over Elements
You can iterate over the elements in a LinkedList using a for loop, an enhanced for loop, or an Iterator:
import java.util.LinkedList;
import java.util.Iterator;
public class IterateLinkedList {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("Using for loop:");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("Using enhanced for loop:");
for (String fruit : list) {
System.out.println(fruit);
}
System.out.println("Using iterator:");
Iterator< String > iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
This example shows three different ways to iterate over a LinkedList.
5. Common Methods
Here are some commonly used methods of the LinkedList class:
add(E e): Adds an element to the end of the list.addFirst(E e): Adds an element to the beginning of the list.addLast(E e): Adds an element to the end of the list.remove(Object o): Removes the first occurrence of the specified element.get(int index): Returns the element at the specified position in the list.
public class CommonLinkedListMethods {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("List size: " + list.size());
list.addFirst("Strawberry");
list.addLast("Blueberry");
list.remove("Banana");
System.out.println("List after modification: " + list);
}
}
This example demonstrates some common methods used with a LinkedList.
Java HashMap
The HashMap class is part of the java.util package and implements the Map interface. It provides a way to store key-value pairs where each key is unique, and it allows for fast retrieval, insertion, and deletion of key-value pairs.
1. Creating a HashMap
To use a HashMap, you need to import it from the java.util package and then instantiate it:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println(map);
}
}
This example creates a HashMap with String keys and Integer values, and adds three key-value pairs.
2. Accessing Elements
You can access values in a HashMap using the get() method by specifying the key:
import java.util.HashMap;
public class AccessHashMapElements {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
Integer value = map.get("Banana");
System.out.println("Value for 'Banana': " + value);
}
}
This example retrieves the value associated with the key "Banana".
3. Removing Elements
You can remove key-value pairs from a HashMap using the remove() method:
import java.util.HashMap;
public class RemoveHashMapElements {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println("Before removal: " + map);
map.remove("Banana");
System.out.println("After removal: " + map);
}
}
This example demonstrates removing an element by its key.
4. Iterating Over Entries
You can iterate over the entries of a HashMap using a for loop, an enhanced for loop, or an Iterator:
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
public class IterateHashMap {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println("Using entrySet:");
for (Map.Entry< String, Integer > entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
System.out.println("Using keySet:");
for (String key : map.keySet()) {
System.out.println(key + " : " + map.get(key));
}
System.out.println("Using iterator:");
Iterator< Map.Entry< String, Integer > > iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry< String, Integer > entry = iterator.next();
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}
This example shows three different ways to iterate over a HashMap.
5. Common Methods
Here are some commonly used methods of the HashMap class:
put(K key, V value): Associates the specified value with the specified key.get(Object key): Returns the value associated with the specified key.remove(Object key): Removes the mapping for the specified key.containsKey(Object key): Returnstrueif the map contains a mapping for the specified key.size(): Returns the number of key-value mappings in the map.
public class CommonHashMapMethods {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println("Size of map: " + map.size());
System.out.println("Value for 'Cherry': " + map.get("Cherry"));
System.out.println("Contains key 'Banana': " + map.containsKey("Banana"));
map.remove("Banana");
System.out.println("Map after removal: " + map);
}
}
This example demonstrates some common methods used with a HashMap.
Java HashSet
The HashSet class is part of the java.util package and implements the Set interface. It represents a collection that does not allow duplicate elements and does not guarantee any specific order of its elements. It is backed by a hash table, making it efficient for basic operations like add, remove, and contains.
1. Creating a HashSet
To use a HashSet, you need to import it from the java.util package and then instantiate it:
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
System.out.println(set);
}
}
This example creates a HashSet with String elements and adds three elements to it.
2. Accessing Elements
You cannot access elements in a HashSet directly by index. Instead, you can iterate over the elements:
import java.util.HashSet;
public class AccessHashSetElements {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
for (String fruit : set) {
System.out.println(fruit);
}
}
}
This example demonstrates iterating over the elements of a HashSet.
3. Removing Elements
You can remove elements from a HashSet using the remove() method:
import java.util.HashSet;
public class RemoveHashSetElements {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
System.out.println("Before removal: " + set);
set.remove("Banana");
System.out.println("After removal: " + set);
}
}
This example shows how to remove an element from a HashSet.
4. Checking for Existence
You can check if a HashSet contains a specific element using the contains() method:
import java.util.HashSet;
public class CheckHashSetContains {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
System.out.println("Contains 'Banana': " + set.contains("Banana"));
System.out.println("Contains 'Grapes': " + set.contains("Grapes"));
}
}
This example demonstrates how to check if a HashSet contains a particular element.
5. Common Methods
Here are some commonly used methods of the HashSet class:
add(E e): Adds the specified element to the set.remove(Object o): Removes the specified element from the set.contains(Object o): Returnstrueif the set contains the specified element.size(): Returns the number of elements in the set.isEmpty(): Returnstrueif the set is empty.
public class CommonHashSetMethods {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
System.out.println("Size of set: " + set.size());
System.out.println("Contains 'Apple': " + set.contains("Apple"));
System.out.println("Is set empty: " + set.isEmpty());
set.clear();
System.out.println("Set after clear: " + set);
}
}
This example demonstrates some common methods used with a HashSet.
Java Iterator
The Iterator interface in Java is part of the java.util package and provides a way to iterate over collections such as ArrayList, HashSet, and LinkedList. It allows for traversing through the elements of a collection, and it supports removing elements from the collection during iteration.
1. Creating an Iterator
You obtain an Iterator from a collection by calling its iterator() method. Here’s how you can create an Iterator and use it:
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println(fruit);
}
}
}
This example demonstrates how to create an Iterator from an ArrayList and iterate through its elements.
2. Removing Elements
The Iterator interface supports removing elements from the collection during iteration using the remove() method:
import java.util.HashSet;
import java.util.Iterator;
public class RemoveUsingIterator {
public static void main(String[] args) {
HashSet<String> set = new HashSet<String>();
set.add("Apple");
set.add("Banana");
set.add("Cherry");
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
if (fruit.equals("Banana")) {
iterator.remove();
}
}
System.out.println("Set after removal: " + set);
}
}
This example shows how to remove elements from a HashSet using an Iterator.
3. Common Methods
The Iterator interface provides the following key methods:
hasNext(): Returnstrueif there are more elements to iterate over.next(): Returns the next element in the iteration.remove(): Removes the last element returned by the iterator (optional operation).
public class IteratorMethods {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String fruit = iterator.next();
System.out.println("Next item: " + fruit);
if (fruit.equals("Banana")) {
iterator.remove();
System.out.println("Removed 'Banana'");
}
}
System.out.println("List after iteration: " + list);
}
}
This example demonstrates the use of hasNext(), next(), and remove() methods of the Iterator interface.
Comments (0)
No comments yet. Be the first to comment!