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
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.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
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 :
- 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.
- 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 Collectionc = 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
- int size : Returns size of collection.
- boolean isEmpty : Returns true if collection is empty.
- boolean contains(Object o) : Returns true if Object o exists in collection.
- Iterator
iterator() : Returns a iterator pointing to a collection. - Object[] toArray() : Coverts a collection to a array of Object type.
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. - boolean add(E e) : Adds element e to the collection. Returns true if operation is successfull.
- boolean remove(Object o) : Removes a object o from the collection. Returns true if operation is successfull.
- 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.
- boolean removeAll(Collection> c) : Removes element of collection c from the caller collection. Returns true if operation is successfull.
- boolean retainAll(Collection> c) : Retains only the elements present in collection c.
- 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 CustomCollectionimplements 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:
- Ordered Collection: A List preserves the insertion order of elements, meaning elements can be accessed by their index.
- Allows Duplicates: A List can contain duplicate elements, unlike sets which do not allow duplicates.
- Positional Access: Elements in a List can be accessed, added, or removed by their index.
- 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.
- void add(int index, E element): Inserts the specified element E at the specified index in this list.
- E get(int index): Returns the element at the specified position in this list.
- E remove(int index): Removes the element at the specified position in this list.
- E set(int index, E element): Replaces the element at the specified position in this list with the specified element.
- 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.
- 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.
- 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) { Listlist = 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); } }
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