Java Collection of Objects Example
19 Java Collection Classes With Examples
Basic concepts every Java programmer should know
In this post, I will show the main methods of the Collection framework used to handle data in Java. This framework provides an architecture for storing and manipulating different objects through different interfaces and implementations.
List
The List interface is defined in Java.util
package. It includes the index-based methods to insert, update, delete and search the elements. It can have duplicate and null elements also.
public interface List<E> extends Collection<E>
Array — ArrayList
Array
The Array class is an implementation of the List interface. This class can contain multiple values, unlike a regular variable containing only a single value.
Example:
//Need to specify the size for array
int[] array1 =
new int[4]; array1[0] = 1;
array1[1] = 2;
array1[2] = 3;
array1[3] = 4;
ArrayList
The ArrayList
implementation of the List interface is one of the most widely used and does not require synchronized access.
In both, we can get any data located at an index position.
Example:
//It is not necessary to specify the size
ArrayList<Integer> array2 =
new ArrayList<Integer>(); array2.add(1);
array2.add(2);
An Array
is a fixed-length data structure, whereas ArrayList
is a variable-length Collection class.
We cannot store primitives in ArrayList
; it can only store objects. But array can contain both primitives and objects.
Vector
public class Vector<E> extends Object<E> implements List<E>, Cloneable, Serializable
This class is used to implement the List interface. Still, it is rarely used because it is a List structure that is always accessed synchronously, which reduces performance in many cases.
We can store n elements in it as there is no size limit.
This implementation contains many legacy methods that are not part of a collections framework.
Example:
//Create Integer type vector
Vector<Integer> vector=
new Vector<>(); vector.add(1); //Using index number
vector.add(2, 2);
Stack
public class Stack<E> extends Vector<E>
The Stack class is a class of LIFO (Last In — First Out) that implements the List class and extends de Vector Class with five operations that allow a vector to be treated as a stack.
The basic operations are push (which pushes an element onto the stack), pop (which pops an element off the stack), peek (queries the first element on the top of the stack), empty (which checks if the stack is empty) and search (which searches for a given element within the stack and returns its position within the stack).
Example:
Stack<Integer> stack =
new Stack<Integer>(); stack.push(1);
stack.pop();//1
LinkedList
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable
This class is almost identical to the ArrayList
because they implement the List interface. We can add, modify, and remove items similarly, but they are built differently.
The ArrayList
class has a regular array inside it. When an element is added, it is placed into the array. If the array size isn't sufficient, a new larger array is created to replace the old one, and the old one is removed. The LinkedList
uses a doubly linked list to store the elements.
This implementation has a better performance when manipulating data because it uses a doubly linked list, so no bit shifting is required in memory. On the other hand, ArrayList
is better for storing and accessing data.
Both are non-synchronized classes.
Example:
LinkedList<String> l
= new LinkedList<String>(); l.add("a");
l.add("b"); //Iterating LinkedList
Iterator<String> iterator = l.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
//a, b
}
Map
public interface Map<K,V>
The Map interface is used to match a key value and a value or object. A map supports any object. However, a map cannot have duplicate keys.
Remember that the equals and hashCode
methods are not helpful on a generic map, so you have to overwrite them to make them work according to your needs.
A Map
can't be traversed, so you need to convert it into Set using the entrySet
method or the keySet
method.
HashMap
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
A HashMap
is one of the implementations of the Map interface; this interface is a type of Collection that stores data associating a key to a value, but it doesn't maintain any order.
The HashMap
works on the hashing principle by assigning a location to a key with the Java hashCode()
method.
Example:
HashMap<String, Integer> numbers
= new HashMap<String, Integer>(); numbers.put("one", 1)
numbers.put("two", 2) System.out.println(numbers.get("one"));
//1
LinkedHashMap
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
LinkedHashMap
implements extend the HashMap
class that implements the Map interface. It maintains insertion order.
LinkedHashMap
is like HashMap
but with an additional feature that maintains insertion order.
Example:
LinkedHashMap<Integer, String> lmap
= new LinkedHashMap<>(); lmap.put(1, null);
lmap.put(2, "two"); System.out.println(lmap.get(1));
//null
SortedMap
public interface SortedMap<K, V> extends Map<K, V>
This interface is very similar to the Map interface. However, it differs in that SortedMap
allows the elements within the Collection set to be fully sorted, making access in searches and queries faster.
The elements are ordered by their key elements.
TreeMap
public class TreeMap<K, V> extends AbstractMap<K, V> implements NavigableMap<K, V>, Cloneable, Serializable; public interface NavigableMap<K,V> extends SortedMap<K,V>;
The TreeMap
is based on a tree implementation that allows having an ordered map. It maintains ascending order.
TreeMap
in Java does not allow null keys (like Map). However, multiple null values can be associated with different keys.
Example:
Example: SortedMap<Integer, String> tm
= new TreeMap<Integer, String>(); tm.put(new Integer(2), "a");
tm.put(new Integer(3), "b");
tm.put(new Integer(5), "c");
tm.put(new Integer(4), "d");
tm.put(new Integer(1), "e"); Set s = tm.entrySet();
Iterator i = s.iterator(); while (i.hasNext()) {
Map.Entry m = (Map.Entry)i.next();
System.out.println((String)m.getValue());
} //e
//a
//b
//d
//c
ConcurrentHashMap
public class ConcurrentHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>, Serializable
ConcurrenthashMap
is similar to HashMap
but with the difference that it is reliable if used by more than one thread. So, it is thread-safe i.e., multiple threads can operate on a single object without any complications.
Inserting null objects is neither possible in ConcurrentHashMap
as a key or value.
Example:
ConcurrentHashMap<String, Integer> days =
new ConcurrentHashMap<String, Integer>(); days.put("monday", Integer.valueOf(1));
days.put("saturday", Integer.valueOf(2)); System.out.println(days.get("monday"));
//1
Set
public interface Set<E> extends Collection<E>
The Set
interface defines a Collection
that cannot contain duplicate elements.
The elements in a Set have no guaranteed internal order in contrast with List. However, the elements in a List have internal order, and we can iterate them using that order.
HashSet
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
This class implements the Set interface and defines the concept of Set (group of non-repeating elements) through a Hash structure.
It is not guaranteed that the objects we insert in a HashSet
will be inserted in the same order. This is because objects are inserted based on their hash code.
A HashSet
does not allow repeated objects, but null elements are allowed.
Example:
HashSet<String> hset =new HashSet();
hset.add("b");
hset.add("a"); //This will not add new element as "a" already exists
hset.add("a");
hset.add("c"); Iterator<String> i=hset.iterator();
while(i.hasNext()) {
System.out.println(i.next());
}
//a
//c
//b
LinkedHashSet
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable
This class extends the HashSet
class and defines the set concept by adding a doubly-linked list in the equation that ensures that the elements are always traversed in the same way.
Therefore, LinkedHashSet
is the sorted version of HashSet
.
Example:
LinkedHashSet<String> linkedset
= new LinkedHashSet<String>(); linkedset.add("A");
linkedset.add("B");
linkedset.add("C"); System.out.println(linkedset);
[A, B, C]
SortedSet
public interface SortedSet<E> extends Set<E>
The SortedSet
interface extends the Set
interface and declares the behavior of a set sorted in ascending order.
TreeSet
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable
This class uses a tree structure, allowing the elements to be ordered either by natural order or by order defined by a Comparator
. In addition, this class helps compare the elements, such as greater than or less than.
Example:
SortedSet<String> ts
= new TreeSet<String>(); ts.add("A");
ts.add("C");
ts.add("B"); Iterator<String> i = ts.iterator();
while (i.hasNext()){
System.out.println(i.next());
} //A
//B
//C
Queue
public interface Queue<E> extends Collection<E>
The Queue
interface stores items and processes them in FIFO (First In First Out) order.
It is an ordered list of objects whose use is limited to the insertion of elements at the end of the List and the deletion of elements from the beginning of the List
following the FIFO (First-In-First-Out) principle.
PriorityQueue
public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable
This class sorts elements based on their natural order, as specified by the Comparable
method or by defining a Comparator
object. This class allows insertions in order and deletions from the front. The insertion is done according to a priority so that the element with the highest priority is placed first.
The most common operations are:
- offer: to insert in a position according to priority.
- poll: for unpacking.
- peek: to get the first in the queue.
- clear: to remove all elements in the queue.
- size: to get the number of elements in the queue.
Example:
PriorityQueue<Integer> pQueue
=new PriorityQueue<Integer>(); pQueue.add(1);
pQueue.add(2);
pQueue.add(3); //Printing the top element of PriorityQueue
System.out.println(pQueue.peek()); //1 //Printing the top element and removing it.
System.out.println(pQueue.poll());
//1 //Printing the top element again
System.out.println(pQueue.peek());
//2
ConcurrentLinkedQueue
public class ConcurrentLinkedQueue<E> extends AbstractQueue<E> implements Queue<E>, Serializable
This class implements the Queue interface and orders elements FIFO (first-in-first-out).
ConcurrentLinkedQueue
is appropriate when many threads share access to a common collection because it does not block the accessing thread when the queue is empty and returns null.
This class does not permit null elements.
BlockingQueue
public interface BlockingQueue<E> extends Queue<E>
This interface extends the Queue
interface. This interface aims to allow any operation to wait until it can be performed successfully.
For example, if we want to delete an item from an empty queue, this type of queue allows the delete operation to wait until the queue contains items to be deleted.
ArrayBlockingQueue
public class ArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable
The ArrayBlockingQueue
class implements the BlockingQueue
interface.
This blocking queue is a fixed-size queue. Therefore, attempts to put an item into a full queue will block the operation. Similarly, attempts to take an element from an empty queue will also be blocked.
LinkedBlockingQueue
public class LinkedBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable
This class also implements the BlockingQueue
interface.
The LinkedBlockingQueue
keeps the elements internally in a linked structure. The LinkedBlockingQueue
stores the elements internally in FIFO (First In, First Out) order.
LinkedBlockingQueue
is a blocking queue. So, it blocks the accessing threads when the queue is empty.
Source: https://betterprogramming.pub/19-java-collection-classes-with-examples-1597f106d0f2
0 Response to "Java Collection of Objects Example"
Post a Comment