Java Utillity
Java Utillity
• T – Type
• E – Element
• K – Key
• N – Number
• V – Value
Collections Class in Java
• Collections class in Java is one of the utility classes in Java Collections
Framework. The java.util package contains the Collections class in Java. Java
Collections class is used with the static methods that operate on the
collections or return the collection. All the methods of this class throw
the NullPointerException if the collection or object passed to the methods
is null.
• Collection Class declaration
• The syntax of the Collection class declaration is mentioned below:
• public class Collections extends Object
Note: Object is the parent class of all the
classes.
• Java Collection Class
• Collection Framework contains both classes and interfaces.
• 1. ArrayList
• ArrayList is a class implemented using a list interface, in that provides the
functionality of a dynamic array where the size of the array is not fixed.
• Syntax:
• ArrayList<_type_> var_name = new ArrayList<_type_>();
• 2. Vector
• Vector is a Part of the collection class that implements a dynamic array that
can grow or shrink its size as required.
• Syntax:
• public class Vector<E> extends AbstractList<E> implements List<E>,
RandomAccess,
• Cloneable, Serializable
ArrayList in Java
• Java ArrayList is a part of the Java collection framework and it is a class of
java.util package. It provides us with dynamic arrays in Java.
• It may be slower than standard arrays but can be helpful in programs where lots of
manipulation in the array is needed.
• The main advantage of Java ArrayList is, if we declare an array then we need to
mention the size, but in ArrayList, it is not needed to mention the size of ArrayList.
What is ArrayList in Java?
• ArrayList is a Java class implemented using the List interface. Java ArrayList, as the
name suggests, provides the functionality of a dynamic array where the size is not
fixed as an array. Also, as a part of the Collection framework, it has many features
not available with arrays.
•
illustration
how to create and use an ArrayList with a mention of its size.
• import java.io.*;
• import java.util.*;
• class ArrayListExample {
• public static void main(String[] args)
• { // Size of the ArrayList
• int n = 5;
• // Declaring the ArrayList with initial size n
• ArrayList<Integer> arr1 = new ArrayList<Integer>(n);
• // Declaring the ArrayList
• ArrayList<Integer> arr2 = new ArrayList<Integer>();
• // Printing the ArrayList
• System.out.println("Array 1:" + arr1);System.out.println("Array 2:" + arr2);
• // Appending new elements at the end of the list
• for (int i = 1; i <= n; i++) { arr1.add(i); arr2.add(i); }
• // Printing the ArrayList
• System.out.println("Array 1:" + arr1);
• System.out.println("Array 2:" + arr2); }}
Output
• Array 1:[]
• Array 2:[]
• Array 1:[1, 2, 3, 4, 5]
• Array 2:[1, 2, 3, 4, 5]
Explanation of the above Program:
• ArrayList is a dynamic array and we do not have to specify the size while creating it, the size
of the array automatically increases when we dynamically add and remove items. Though the
actual library implementation may be more complex, the following is a very basic idea
explaining the working of the array when the array becomes full and if we try to add an
item:
• Creates a bigger-sized memory on heap memory (for example memory of double size).
• Copies the current memory elements to the new memory.
• The new item is added now as there is bigger memory available now.
• Delete the old memory.
Important Features of ArrayList in Java
• ArrayList inherits AbstractList class and implements the List interface.
• ArrayList is initialized by size. However, the size is increased automatically if
the collection grows or shrinks if the objects are removed from the
collection.
• Java ArrayList allows us to randomly access the list.
• ArrayList can not be used for primitive types like int, char, etc. We need a
wrapper class for such cases.
• ArrayList in Java can be seen as a vector in C++.
• ArrayList is not Synchronized. Its equivalent synchronized class in Java is
Vector.
Hierarchy Java ArrayList
Constructors in ArrayList
• In order to create an ArrayList, we need to create an object of the ArrayList
class. The ArrayList class consists of various constructors which allow the
possible creation of the array list. The following are the constructors
available in this class:
• 1. ArrayList()
• This constructor is used to build an empty array list. If we wish to create an
empty ArrayList with the name arr, then, it can be created as:
• ArrayList arr = new ArrayList();
• 2. ArrayList(Collection c)
• This constructor is used to build an array list initialized with the elements
from the collection c. Suppose, we wish to create an ArrayList arr which
contains the elements present in the collection c, then, it can be created as:
• ArrayList arr = new ArrayList(c);
• 3. ArrayList(int capacity)
• This constructor is used to build an array list with the initial capacity being
specified. Suppose we wish to create an ArrayList with the initial size being
N, then, it can be created as:
• After adding the elements, if we wish to change the element, it can be done
using the set() method. Since an ArrayList is indexed, the element which we
wish to change is referenced by the index of the element. Therefore, this
method takes an index and the updated element which needs to be inserted
at that index.
• // Java Program to Change elements in ArrayList
• // Importing all utility classes
• import java.util.*;
• // main class
• class chel {
• // Main driver method
• public static void main(String args[])
• { // Creating an Arraylist object of string type
• ArrayList<String> al = new ArrayList<>();
• // Adding elements to Arraylist
• // Custom input elements
• al.add("Greet"); al.add("Greet");
• // Adding specifying the index to be added
• al.add(1, "hello");
• // Printing the Arraylist elements
• System.out.println("Initial ArrayList " + al);
• // Setting element at 1st index
• al.set(1, "For");
• // Printing the updated Arraylist
• System.out.println("Updated ArrayList " + al); }}
3. Removing Elements
• In order to remove an element from an ArrayList, we can use the remove()
method. This method is overloaded to perform multiple operations based on
different parameters. They are as follows:
• remove(Object): This method is used to simply remove an object from the
ArrayList. If there are multiple such objects, then the first occurrence of the
object is removed.
• remove(int index): Since an ArrayList is indexed, this method takes an
integer value which simply removes the element present at that specific index
in the ArrayList. After removing the element, all the elements are moved to
the left to fill the space and the indices of the objects are updated.
• // Java program to Remove Elements in ArrayList
• // Importing all utility classes
• import java.util.*;
• class GRem{
• public static void main(String args[])
• { rrayList<String> al = new ArrayList<>();
• // Adding elements to ArrayList
• // Custom addition
• al.add("Great"); al.add("Great");
• // Adding element at specific index
• al.add(1, "For");
• // Printing all elements of ArrayList
• System.out.println("Initial ArrayList " + al);
• // Removing element from above ArrayList
• al.remove(1);
• // Printing the updated Arraylist elements
• System.out.println("After the Index Removal " + al);
• // Removing this word element in ArrayList
• al.remove("Great");
• // Now printing updated ArrayList
• System.out.println("After the Object Removal "+ al); }}
4. Iterating the ArrayList
• There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination
with a get() method to get the element at a specific index and the advanced for a loop.
• import java.util.*;
• class GFG {
• // Main driver method
• public static void main(String args[])
• { ArrayList<String> al = new ArrayList<>();
• // Adding elements to ArrayList
• // using standard add() method
• al.add("Geeks");
• al.add("Geeks");
• al.add(1, "For");
• // Using the Get method and the
• // for loop
• for (int i = 0; i < al.size(); i++) {
• System.out.print(al.get(i) + " "); }
• System.out.println();
• for (String str : al)
• System.out.print(str + " "); }}
• ArrayList in Java is a class in the Java Collection framework that implements the List
interface. Here are the advantages and disadvantages of using ArrayList in Java.
• Slower than arrays: ArrayList is slower than arrays for certain operations, such as
inserting elements in the middle of the list.
• Increased memory usage: ArrayList requires more memory than arrays, as it needs
to maintain its dynamic size and handle resizing.
• Not thread-safe: ArrayList is not thread-safe, meaning that multiple threads may
access and modify the list concurrently, leading to potential race conditions and data
corruption.
• Performance degradation: ArrayList’s performance may degrade as the number of
elements in the list increases, especially for operations such as searching for
elements or inserting elements in the middle of the list.
Points to be noted
• ArrayList is the part of Collection framework. It inherits the AbstractList
class and implements the List interface.
• ArrayList is the implementation of a dynamic array.
• ArrayList can be initialized used using different constructor types like
without parameters, passing collection as a parameter, and passing integer as
a parameter.
• Operations can be performed in ArrayList as follows Adding, removing,
iterating, and sorting.
vector
• Vector implements a dynamic array which means it can grow or shrink as
required. Like an array, it contains components that can be accessed using an
integer index.
• They are very similar to ArrayList, but Vector is synchronized and has some
legacy methods that the collection framework does not contain.
• It also maintains an insertion order like an ArrayList. Still, it is rarely used in
a non-thread environment as it is synchronized, and due to this, it gives a
poor performance in adding, searching, deleting, and updating its elements.
syntax
• public class Vector<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable
• It extends AbstractList and implements List interfaces.
• It implements Serializable, Cloneable, Iterable<E>, Collection<E>,
List<E>, RandomAccess interfaces.
• The directly known subclass is Stack.
Constructors
1. Vector(): Creates a default vector of the initial capacity is 10.
• Vector<E> v = new Vector<E>();
2. Vector(int size): Creates a vector whose initial capacity is specified by size.
• Vector<E> v = new Vector<E>(int size);
3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size
and increment is specified by incr. It specifies the number of elements to allocate each
time a vector is resized upward.
• The main difference between a normal linked list and a doubly LinkedList is that a doubly
linked list contains an extra pointer, typically called the previous pointer, together with the
next pointer and data which are there in the singly linked list.
Constructors in the LinkedList:
Method Description
• Dynamic size: As with Vector, the size of a LinkedList can grow or shrink
dynamically, so you don’t have to worry about setting an initial size.
• Efficient Insertions and Deletions: LinkedList is an efficient data structure for
inserting or deleting elements in the middle of the list because you only need to
change the links between elements, rather than shifting all elements after the
insertion or deletion point.
• Flexible Iteration: With a linked list, you can efficiently iterate through the list in
either direction, since each element has a reference to both its predecessor and
successor elements.
Disadvantages of using LinkedList in Java:
SN Constructor Description
1) HashSet() It is used to construct a default HashSet.
2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer value
capacity. The capacity grows automatically as elements are added to the
HashSet.
A list can contain duplicate elements whereas Set contains unique elements only.
The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order. import java.util.*;
A HashSet is a collection of items where every item is unique, and it is found in the java.util
package:
• class HashSet1{
• public static void main(String args[]){
• //Creating HashSet and adding elements
• HashSet<String> set=new HashSet();
• set.add("One");
• set.add("Two");
• set.add("Three");
• set.add("Four");
• set.add("Five");
• Iterator<String> i=set.iterator();
• while(i.hasNext())
• {
• System.out.println(i.next());
• }
• }
• }
Hashset for storing integers
• import java.util.HashSet;
• public class Main {
• public static void main(String[] args) {
• // Create a HashSet object called numbers
• HashSet<Integer> numbers = new HashSet<Integer>();
• // Add values to the set
• numbers.add(4);
• numbers.add(7);
• numbers.add(8);
• // Show which numbers between 1 and 10 are in the set
• for(int i = 1; i <= 10; i++) {
• if(numbers.contains(i)) {
• System.out.println(i + " was found in the set.");
• } else {
• System.out.println(i + " was not found in the set."); } } }}
Java Iterator
• An Iterator is an object that can be used to loop through collections, like
ArrayList and HashSet. It is called an "iterator" because "iterating" is the
technical term for looping.
• import java.util.ArrayList;
• import java.util.Iterator;
• public class Main {
• public static void main(String[] args) {
• ArrayList<Integer> numbers = new ArrayList<Integer>();
• numbers.add(12);
• numbers.add(8);
• numbers.add(2);
• numbers.add(23);
• Iterator<Integer> it = numbers.iterator();
• while(it.hasNext()) {
• Integer i = it.next();
• if(i < 10) {
• it.remove(); } }
• System.out.println(numbers); }}
Java HashMap
• In the ArrayList chapter, you learned that Arrays store items as an ordered
collection, and you have to access them with an index number (int type). A
HashMap however, store items in "key/value" pairs, and you can access them
by an index of another type (e.g. a String).
• One object is used as a key (index) to another object (value). It can store
different types: String keys and Integer values, or the same type, like: String
keys and String values:
• Create a HashMap object called capitalCities that will store String keys and
String values:
• import java.util.HashMap; // import the HashMap class
• HashMap<String, String> capitalCities = new HashMap<String, String>();
Hashmap classes
• import java.util.HashMap;
• Adding elements
• Accessing elements
• Removing elements
• Iterating through elements