"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > JAVA COLLECTION FRAMEWORK

JAVA COLLECTION FRAMEWORK

Published on 2024-11-07
Browse:540

Que What is Java Collection Framework?

Ans Java Collection framework is a powerful built-in library that provides set of optimised implementaions of most commonly used data structures and algorithms.It is widely utilized in building Java applications and solving real-world software development challenges.


Que Advantages of Java Collection Framework?

Ans Some of the advantages of Java Collection framework are

  1. Unified Architecture : Every data structure is derived from interfaces such as iterable interface and collection interface providing a sense of common implementations.
  2. Ease of use : It simplifies the development process by providing pre-built data structures and algorithms. The developer can focus more on business logic rather than manually implementing and optimising commonly used data structures and standard algorithms.
  3. Flexibility : If we want to change underlying data structures, we can do it easily without worrying that changing data structure will change data retrieval and access patterns(mostly).
  4. Thread Safety : As java provides a way to run processes on different threads individually, Java Collection Framework provides different classes to run in multithread envorinments and single threaded applications.

JAVA COLLECTION FRAMEWORK HIERARCHY

JAVA COLLECTION FRAMEWORK


ITERABLE INTERFACE
The Iterable interface in Java is a key component of the Collection Framework. It is the root interface for all collection types that can be iterated over. Implementing the Iterable interface allows an object to be the target of a "for-each loop" (also known as the enhanced for loop).
Also it provides a iterator object that can be used for forward iteration of all data structures that implements this iterable interface.

Example using FOR EACH LOOP (ENHANCED FOR LOOP)

Internally ArrayList implements List and List Interface extends Collection Interface and Collection Interface extends Iterable Interface.

List list = new ArrayList();//Declaring a Data Structure
list.add("Java");//Add element
list.add("Collections");//Add element
list.add("Framework");//Add element
for (String element : list) {//Iterating using enhanced for loop
System.out.println(element);
}

Example using ITERABLE Object

Iterator iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}

So we can create custom iterable implementing iterable interface and overriding next,hasNext and remove method. Here is example of the same.

import java.util.Iterator;
class CustomIterable implements Iterable {
    private final int[] numbers = {1, 2, 3, 4, 5};

    @Override
    public Iterator iterator() {
        return new Iterator() {
            private int index = 0;
            private int lastReturnedIndex = -1;

            @Override
            public boolean hasNext() {
                return index 



Note :

  1. Iterators in Java are fail-fast. This means that if the collection is modified while iterating (except through the iterator’s own remove() method), it throws a ConcurrentModificationException.
  2. The remove() method can only remove elements, and it should be called only once per call to next(). Otherwise, it will throw an IllegalStateException.

Collection Interface

This is the interface through which the data structures and inner implementations become flexible. Majorly all the classes implement this interface indirectly allowing changing implementation by just changing object assigned to Collection reference of it.

//ArrayList
Collection c = new ArrayList():
c.add(1);
c.add(2);
c.contains(1);

Collection c1 = new LinkedList():
c1.addAll(c);//Array added to a linked list

/*What if i dont want arraylist but now i want a priority queue for applying efficient algorithms such as findmax and find min*/
//Just Change Object - SIMPLE!
Collection c = new **PriorityQueue**():
c.add(1);
c.add(2);
c.contains(1);

Methods of Collection Interface

  1. int size : Returns size of collection.
  2. boolean isEmpty : Returns true if collection is empty.
  3. boolean contains(Object o) : Returns true if Object o exists in collection.
  4. Iterator iterator() : Returns a iterator pointing to a collection.
  5. Object[] toArray() : Coverts a collection to a array of Object type.
  6. T[] toArray(T[] a) : Returns an array containing all elements of the collection; the runtime type of the returned array is that of the specified array.
  7. boolean add(E e) : Adds element e to the collection. Returns true if operation is successfull.
  8. boolean remove(Object o) : Removes a object o from the collection. Returns true if operation is successfull.
  9. boolean containsAll(Collection> c) : Returns true if all elements in both collections are same. Returns true if operation is successfull. 10.boolean addAll(Collection extends E> c) : Adds all element of both the collections. Returns true if operation is successfull.
  10. boolean removeAll(Collection> c) : Removes element of collection c from the caller collection. Returns true if operation is successfull.
  11. boolean retainAll(Collection> c) : Retains only the elements present in collection c.
  12. void clear() : Clears all the elements from the collection.

By implementing collection class we can override above methods to create a custom collection. Below is example for same.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class CustomCollection implements Collection {
    private final ArrayList list = new ArrayList();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return list.contains(o);
    }

    @Override
    public Iterator iterator() {
        return new Iterator() {
            private int index = 0;

            @Override
            public boolean hasNext() {
                return index  T[] toArray(T[] a) {
        return list.toArray(a);
    }

    @Override
    public boolean add(E e) {
        return list.add(e);
    }

    @Override
    public boolean remove(Object o) {
        return list.remove(o);
    }

    @Override
    public boolean containsAll(Collection> c) {
        return list.containsAll(c);
    }

    @Override
    public boolean addAll(Collection extends E> c) {
        return list.addAll(c);
    }

    @Override
    public boolean removeAll(Collection> c) {
        return list.removeAll(c);
    }

    @Override
    public boolean retainAll(Collection> c) {
        return list.retainAll(c);
    }

    @Override
    public void clear() {
        list.clear();
    }
}


List Interface

The List interface in Java is a part of the Java Collections Framework and extends the Collection interface. It represents an ordered collection (also known as a sequence) that allows for positional access, duplicate elements, and iteration over its elements. The List interface is implemented by several classes, such as ArrayList, LinkedList, Vector, and Stack.

Key Characteristics of the List Interface:

  1. Ordered Collection: A List preserves the insertion order of elements, meaning elements can be accessed by their index.
  2. Allows Duplicates: A List can contain duplicate elements, unlike sets which do not allow duplicates.
  3. Positional Access: Elements in a List can be accessed, added, or removed by their index.
  4. Iteration: The List interface allows for enhanced for-loops, as well as iteration using Iterator or ListIterator.

Commonly Used Methods of List Interface:
All collection interface methods are also implemented by List interface as List interface extends Collection interface.

  1. void add(int index, E element): Inserts the specified element E at the specified index in this list.
  2. E get(int index): Returns the element at the specified position in this list.
  3. E remove(int index): Removes the element at the specified position in this list.
  4. E set(int index, E element): Replaces the element at the specified position in this list with the specified element.
  5. int indexOf(Object o): Returns the index of the first occurrence of the specified element, or -1 if the list does not contain the element.
  6. int lastIndexOf(Object o): Returns the index of the last occurrence of the specified element, or -1 if the list does not contain the element.
  7. List subList(int fromIndex, int toIndex): Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Java");
        list.add("Collections");
        list.add("Framework");

        // Accessing elements by index
        System.out.println("First Element: "   list.get(0));

        // Removing an element by index
        list.remove(1);
        System.out.println("After Removal: "   list);

        // Updating an element
        list.set(1, "Updated Element");
        System.out.println("Updated List: "   list);

        // Using a sublist
        List sublist = list.subList(0, 1);
        System.out.println("Sublist: "   sublist);
    }
}

Release Statement This article is reproduced at: https://dev.to/harsh_khanpara_e78fd42c5a/java-collection-framework-4fm8?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3