Collection framework:
A Java collection framework provides an architecture to store and manipulate a group of elements or objects
–>It “Provides an architecture” – means it gives a well-structured set of classes and interfaces.
–>”To store, retrieve, and manipulate” – covers the basic operations like adding, removing, searching, sorting, etc.
–>”Group of objects or elements” – refers to data items like integers, strings, user-defined objects, etc.
The primary advantages of a collections framework are that it:
Reduces programming effort by providing data structures and algorithms so you don’t have to write them yourself.
Increases performance by providing high-performance implementations of data structures and algorithms.
collection of classes & collection of interfaces:
Interfaces–>List, Set, Map
classes–> ArrayList,LinkedList, HashSet, TreeSet,LinkedHashSet, HaspMap, TreeMap,LinkedHaspMap
import java.util.*;
class ASC
{
public static void main(String args[])
{
int a[]=new int[5];//fixed size[0-4]
//Dynamic memory allocation
ArrayList<Integer> alist=new ArrayList<Integer>();
alist.add(1);
alist.add(2);
for(int i=1;i<=10;i++)
{
alist.add(i);
}
System.out.println(alist);
/*ArrayList<String> slist=new ArrayList<String>();
slist.add(“John”);
slist.add(“12”);
slist.add(“f”);
System.out.println(slist);*/
alist.add(100);
alist.add(100);
alist.add(100);//therefore arraylist supports redundancy
System.out.println(alist);
System.out.println(alist.get(3));//the value stored in index 3 will be printed
alist.set(0,100);//update based on index
System.out.println(alist);
alist.remove(5);
System.out.println(alist);
//alist.clear();
//System.out.println(alist);
/*Iterator
To access elements sequentially without exposing the underlying structure
To safely remove elements from collection during iteration(like for each)
Syntax:
Iterator<Type> iterator=collection.iterator();
hasNest()–>returns true if elemets exist
next()–>returns the next element
*/
/*Iterator<Integer> i=alist.iterator();
System.out.println(“using iterator”);
System.out.println(i.next());*/
Iterator<Integer> i=alist.iterator();
System.out.println(“using iterator”);
while(i.hasNext())
{
System.out.println(i.next());
}
//get–>will not remove the particular element from the arraylist
//remove–>will remove the particular element from the arraylist
}}