Java
collection frameworks:
DisAdvantages
of array :
Fixed Size:
- The
size of an array is fixed at the time of creation, and it cannot be
increased or decreased dynamically.
- You
can only store a fixed number of values.
- Example:
int[] iarr = new int[5]; – This array can hold exactly 5 integers
Lack of Predefined
Methods:
- Adding
Values: There is no predefined method to add a value to an array once it's
created.
- Deleting
Values: You cannot directly delete a value from an array.
- Inserting
Values: There is no method to insert a value at a specific index in an
array.
- Searching
for Values: There is no built-in method to search for a specific value in
an array to check if the array contains it.
Note:
Accessing Array
Length:
- The
length of an array can be accessed using arr.length.
- Incorrect
Usage: arr.length() – This is incorrect; arrays do not use parentheses for
accessing length.
String Length:
- Unlike
arrays, the length of a String is accessed using s.length().
To overcome all the above disadvantages
of array, we will go for Collection Frame work.
What is Collection Frame Work?
Collection frame work can be used
for storing and manipulating groups of objects.
·
It provides various interfaces and classes that
help in managing and processing collections of objects efficiently.
·
The framework is part of the java.util package and is fundamental to many Java
programs.
Collection : (I)
·
It is predefined interface in java and which has
some predefined methods.
·
It can be used to store group of values /
objects/ elements in a single unit.
Collections: (c)
It
is predefined class in java
Collection framework :
-----------------------
Collection
|
-----------------------------------------------------
| | | | |
List Set Queue Deque Map
| | | | |
ArrayList HashSet
PriorityQueue ArrayDeque HashMap
LinkedList LinkedHashSet
LinkedList LinkedList LinkedHashMap
Vector
TreeSet
- TreeMap
Stack - - Hashtable
-
contains predefined Interfaces and predefined classes
- Method Methods
Interface contains only abtr
amethod
-can be used to handle group of
objects / elements / values
- to add value into collection
- to remove value from collection
- to insert the values in
collection
- to remove all values from
collection
interface Collection extends
Iterable (I)
some methods:
-----------------
add()
remove()
insert()
contains() - to check collection
obj contains given value or not
size() - get count of value in
collection
clear() -- remove all values from
Collection
Some of important Interfaces in collection Frame work:
List Interface (I)
·
Predefined Interface in Java:
·
The List interface is a part of the Java
Collection Framework.
·
It is used to store a collection of
elements or group of values
·
It stores values sequentially 10 -0 , 11 ,-1
·
Or
·
Elements in a List are stored in a sequence,
meaning that each element is associated with an index starting from 0.
·
Example: In a List, the first element (at index
0) could be 10, the second (at index 1) could be 11, and so on.
·
Insertion Order is Preserved:
·
The order in which elements are added to a List
is maintained.
·
Example: If you add elements 10, 20, 30 to a List,
they will be stored in the same order: 10, 20, 30.
10,20,30 --> 10,20,30
·
It allows duplicate values
Example:
A List can have the values 10,
20, 10, 30, where 10 appears twice.
implementation classes :
List(I)
--------------------------------------------------------
ArrayList(C) LinkedList(C) Stack(C)
Vector(C) implements of List -Interface methods
class ArrayList implements List
class LinkedList implememts List
class stack implements List
Set (I):
·
Set is predefined Interface in java
·
The Set
interface is part of the Java Collection Framework
·
Set can be used to store group of values or
elements
·
Set stores values randomly. Elements in a Set are stored in no particular order. The order in
which elements are added is not necessarily preserved.
·
Example: Adding elements 10, 50, 30, 40 to a Set might result in an order like 30, 10, 50, 40.
·
In set, insertion order is not preserved. Unlike List, the Set
does not guarantee the order of elements. The insertion order is not
maintained.
10,50,30,40 --> 30,10,50,40
·
Set does not allow duplicate values. If you try
to add the same element multiple times, it will be stored only once.
·
Example: Adding elements 10, 20, 10, 30 to a Set results in 10, 20, 30, with the duplicate 10
being removed.
10,20,10,30 -->
10,20 ,30
implementation classes :
Set(I)
----------------------------------------------------------------
HashSet(C) LinkedHashSet(C) TreeSet(c) implements
of Set -Interface methods
-------------------------------------------------------------
class HashSet implements Set
class LinkedHashSet implement Set
class TreeSet implememts Set
ArrayList : (C)
·
ArrayList is a predefined class in Java
·
It is a part of the Java Collection Framework.
·
ArrayList can be used to store a group of values
or elements.
·
ArrayList stores values in a sequential order,
with each element associated with an index starting from 0,1,2 etc.
·
Insertion Order is Preserved: The order
in which elements are added to an ArrayList is maintained.
·
An ArrayList can contain duplicate elements.
·
All collection framework classes and interfaces,
including ArrayList, are defined in the java.util package.
public class ArrayListBasics1 {
public
static void main(String[] args) {
package
CollectionFrameBasics;
import java.util.ArrayList;
public class ArrayListBasics1 {
public
static void main(String[] args) {
//
creating obj - for arrayList class and store group of "String" values
ArrayList<String> al =
new ArrayList<String>();
///
initially array list is empty
al.isEmpty();
// can be used yo check aray
list obj is empty or not
// if at all it is empty, this method return
true else false
// we can store group of string values in array
list obj
//
add String values "Ram" , Sita
into arraylist
al.add("Ram");
al.add("sita");
//
display array list obj
System.out.println("Array
List ="+ al);//
//
Array List =[Ram, sita]
//
add Lakshman into array list
al.add("Laskhman");
//
System.out.println("Array
List ="+al);//[Ram,Sita, Lakshman]
//after
adding values, check Arraylist isempty
boolean
isEmpty = al.isEmpty();
// false
//isEmpty
=
System.out.println("isEmpty="+
isEmpty); //
//remove
'Ram' from array list
al.remove("Ram");
//
[Ram,Sita, Lakshman]
--> [Sita, Lakshman]
System.out.println("Array
List after Removing Ram="+ al);
// Array List after Removing
Ram=[sita, Laskhman]
//
get count of array list
int
Count = al.size();
//
used to get count of values from array list
//
System.out.println("count
of array list ="+ Count);//
//
Count of array list = 2
//
check array list conatins value i.e Ram
// [Ram, Sita, Lakshman] contains ""
//
boolean containsRam =
al.contains("Ram");
//
[sita, Laskhman]
System.out.println("containsRam="+
containsRam); // false
//
check array list contains given value i.e sita
boolean
containsSita = al.contains("sita");
// [sita, Laskhman] contains("sita");
// true
// containsSita = true
System.out.println("containsSita="+containsSita);//true
//
remove val from array list based on index no
al.remove(0);
// [ Sita, Lakshman]
// 0
1
// [
Lakshman]
System.out.println("after
removing ,Array list ="+ al);//
[Laskhman]
//
add "Raju" value at index no =0
al.add(0,
"Raju");
//
// [Laskhman]
//
0
// [Raju, Lakshman]
// 0 1
System.out.println("after
adding value at index no =0 ,Array list ="+ al);
//
after adding value at index no =0 ,Array list ==[Raju, Laskhman]
//
get value at index no -0 in array list
String val0 = al.get(0);
// [Raju, Laskhman]
// 0
1
// Raju
//val0 = Raju
System.out.println("val0="+val0);//
Raju
//
get value at index no -1
String
val1= al.get(1);
// Laskhman
//
val1 = Laskhman
System.out.println("val1="+val1);//Laskhman
//
HW add "Sita" into array list
// HW
get value at index no -2
// HW get value at index no -4
String
val4 =al.get(4);
System.out.println("val4="+
val4);//Error java.lang.IndexOutOfBoundsException: Index 4 out of bounds for
length 2
// dont use invalid index no in aray list
}
}
//
creating obj - for arrayList class and store group of String values
// we can store group of string values in array
list obj
///
initially array list is empty
// can be used yo check aray
list obj is empty or not
// if at all it is empty, this method return
true else false
//isEmpty
=
System.out.println("isEmpty=");
//
//
add String values "Ram" , Sita
into arraylist
//
display array list obj
System.out.println("Array
List =");
//
//
add Lakshman into array list
//
System.out.println("Array
List =");//
//after addding values,
check Arraylist isempty
//
System.out.println("isEmpty=");//
//remove
'Ram' from array list
//
-->
System.out.println("Array
List after Removing Ram=");
//
get count of array list
// used to get count of values from array list
//
System.out.println("count
of array list =");//
//
Count of array list =
//
check array list conatins value i.e Ram
// [Ram, Sita, Lakshman] contains ""
//
// containsRam
=
System.out.println("containsRam="); //
//
check array list contains given value i.e Raju
// [Ram, Sita, Lakshman] contains("Raju");
//
// containsRaju =
System.out.println("containsRaju=");//
//
remove val from array list based on index no
// [Ram, Sita, Lakshman]
// 0
1 2
//
System.out.println("after
removing ,Array list =");//
//
add "Raju" value at index no =0
// // [Sita,Lakshman]
// 0
1
//
System.out.println("after
adding value at index no =0 ,Array list =");
// after adding value at index no
=0 ,Array list =
//
get value at index no -0 in array list
System.out.println("val0=");//
//
get value at index no -1
// HW
get value at index no -2
// HW get value at index no -4
}
}
o/p:
Array List =[Ram, sita]
Array List =[Ram, sita, Laskhman]
isEmpty=false
Array List after Removing
Ram=[sita, Laskhman]
count of array list =2
containsRam=false
containsSita=true
after removing ,Array list
=[Laskhman]
after adding value at index no =0
,Array list =[Raju, Laskhman]
val0=Raju
val1=Laskhman
// Note : all collection frame
work classes and interfaces are defined Java.util package
2. We must use import
java.util.ArrayList; stmt before class
definition
ex:
package
ArrayList(C) LinkedList(C) Stack(C)
Vector(C) ---> defined
import : predefined k/w , can be
used to import given class from given packages
-if we want to use any specific
class, we must import package.
import arrayList --> import
java.util.ArrayList;
import LinkedList --> import
java.util.LinkedList;
import Stack --> import
java.util.Stack;
HW Import Hashshet class?
HW Import LinkedHashSet class?
HW import TreeSet -class ?
package CollectionFrameBasics;
import java.util.ArrayList;
public class ArrayListBasics2 {
public
static void main(String[] args) {
//
Create array List of String
ArrayList<String>
al = new ArrayList<String>();
//
add Ram, sita,Raju in array list
al.add("Ram");
al.add("Sita");
al.add("Raju");
System.out.println("Array
list =" + al);
//
al = [Ram, Sita, Raju]
//
clear () can be used to remove all values from array list
al.clear();
System.out.println("Array
list =" + al);
//
al = []
//// add Ram, sita,Raju in array
list
al.add("Ram");
al.add("Sita");
al.add("Raju");
//
get index no of Given String "Ram"
int
indexOfRam = al.indexOf("Ram");
// 0
///
indexOfRam = 0 // 0
//
indexNoRam = 0
System.out.println("indexNoRam
="+indexOfRam);
//
indexNoRam =0
//
Get index no of 'sita'
int
indexOfsita = al.indexOf("Sita");
// 1
// indexOfsita =1
System.out.println("indexOfsita
="+indexOfsita);
// indexOfsita =1
//HW Get index no of 'Raju'
// Get index no of 'Laskhman'
int
indexofLakshman = al.indexOf("Laskhman");
// -1
//
indexofLakshman = -1
//
if given value is not there in array list, indexOf() returns -1 value
System.out.println("indexofLakshman="+indexofLakshman);
// -1
//
indexOfLakshman = -1
}
}
add int values
into array List:
package CollectionFrameBasics;
import java.util.ArrayList;
public class ArrayListOfIntValues
{
public
static void main(String[] args) {
//
create array list of int:
// ArrayList<String>
// ArrayList<int> al =
new ArrayList<int>();
ArrayList<Integer>
al = new ArrayList<Integer>();
// array List , we cannot store any primitive
data types int, float ,char..etc
// collection frame work - can be used handle
group of objects
// Wrapper classes
// int
-Integer
// float
- Float
// char
Character
//
create array list of int
//
add some values into aray list 10 ,20 ,30
// al.add("10");//
CE The method add(Integer) in the type ArrayList<Integer> is not
applicable for the arguments (String)
al.add(10);
al.add(20);
al.add(30);
// al.add("40");
Error : as we are stroing invlaid value
in array list
// in arraylist, we are storing integer values.,
so we should store integer values only
// but not String values
"40" is String
// 40 - int
System.out.println("Al
="+ al);
// [10,20,30]
// 0 1 2
//
remove '20' -- remove
// al.remove(20);//
[10, 20, 30] --> [10, 30]
//
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index
20 out of bounds for length 3
//
// remove the value at index no =1 i.e 20
System.out.println("array
list="+ al);
// [ ]
//HW count of array list . size()
//
HW repeat all previous class
methods for array list
//HW get val at index no = 0
System.out.println("get
val at index no = 0 -");
//
HW get val at index no=1
System.out.println("get
val at index no = 1-");
//HW
get val at index no= 7
System.out.println("get
val at index no = 7 -");
//Exception
in thread "main" java.lang.IndexOutOfBoundsException: Index 7 out of
bounds for length 2
//
Why : bcoz index no =7 is not there in
array list
}
}
Get all values
from Array List:
4 ways
1. for loop with index no
2. For Each loop
3. itertaor()
4. listItertaor()
-----------------------------------------
Get all values
from Collection Frame work (array list , hashset..):
1.
For loop with index no
2.
For each loop
3.
Iterator()
4.
listIterator()
// 100
// get(0)
// get(1)
//
// get(99)
// way 1:
for loop with index no
//
//
way 2: for each loop - can be used to get values from array/ Collection obj
// for(int/String : arr/collection obj)
// {
//
// }
//
//
get each val from array list and store into variable -eachval
System.out.println("values
from array list using for each loop="+ eachval);
package CollectionFrameBasics;
import java.util.ArrayList;
public class
GetAllValuesFromArrayList {
public
static void main(String[] args) {
ArrayList<String>
al = new ArrayList<String>();
al.add("Ram");
al.add("Sita");
al.add("Lakshmna");
// al = [Ram,sita,Lakshman]
// 0
1 2
// way 1:
for loop with index no
for(int
i=0;i<=al.size()-1;i++)
{
String
val = al.get(i);
System.out.println("get
allls from array list="+ val);
}
//
//
way 2: for each loop - can be used to get values from array/ Collection obj
// for(int/String : arr/collection obj)
// { al
//
// }
for(String
eachval : al)
{
System.out.println("all
values from array klist using for each loop -"+ eachval);
}
//
//
get each val from array list and store into variable -eachval
// System.out.println("values
from array list using for each loop="+ eachval);
}
}
o/p:
get allls from array list=Ram
get allls from array list=Sita
get allls from array
list=Lakshmna
all values from array klist using
for each loop -Ram
all values from array klist using
for each loop -Sita
all values from array klist using
for each loop -Lakshmna
// 1
for loop with index no
// get()
can be used to get value at given index no from array list
//
ArrayList of int values:
package CollectionFrameBasics;
import java.util.ArrayList;
public class
ArrayListOfIntValues2 {
public
static void main(String[] args) {
//
create array list of int
ArrayList<Integer>
al = new ArrayList<Integer> ();
//
add some values into aray list 10 ,20 ,30
al.add(10);
al.add(20);
al.add(30);
System.out.println("Al
="+ al);
//
[10,20,30]
// 1. for loop
with index no
// 2. For Each
loop
// 3.
itertaor()
// 4.
listItertaor()
//1
. for loop with index no
//
get val from array list using index no
for(int
i=0;i<=al.size()-1;i++)
{
Integer iref =
al.get(i);
System.out.println("Values
from array list using for loop with index no= "+ iref);
}
}
}
-----------------------------
//2
for each loop: to get values from array
or Collection Object(arraylist, hash set....etc)
// int arr []
= new int [3];
// for(int
eachVal :arr (or) CollectionobjName)
// {
//
// }
package CollectionFrameBasics;
import java.util.ArrayList;
public class
GetValuesUsingForEachLoopFromArrayListOfIntValues {
public
static void main(String[] args) {
//
create array list of int
ArrayList<Integer>
al = new ArrayList<Integer> ();
//
add some values into aray list 10 ,20 ,30
al.add(10);
al.add(20);
al.add(30);
System.out.println("Al
="+ al);
//
[10,20,30]
// 1. for loop
with index no
// 2. For Each
loop
// 3.
itertaor()
// 4.
listItertaor()
// 2. For Each
loop
// for(Integer
ival : al)
for(int
ival : al)
{
System.out.println("get
all values from array list using for each loop:"+ ival);
}
// get
values from array list and store into variable i.e eachVal
}
}
3. get values
from array list using itertaor():
It
gets values in forward direction only.
package CollectionFrameBasics;
import java.util.ArrayList;
import java.util.Iterator;
public class
GetValuesUsingForIteratorFromArrayListOfIntValues {
public
static void main(String[] args) {
//
create array list of int
ArrayList<Integer>
al = new ArrayList<Integer> ();
//
add some values into aray list 10 ,20 ,30
al.add(10);
al.add(20);
al.add(30);
System.out.println("Al
="+ al);
//
[10,20,30]
// 1. for loop
with index no
// 2. For Each
loop
// 3. iterator()
// 4.
listItertaor()
//
////
3 . iterator()
//
Iterator - Predefined Interface in java lang
//
can be used to iterate values from ArrayList
// get values from Array list
// // get val
from array list
Iterator<Integer>
it = al.iterator();
// Integer iref1 = it.next();
// System.out.println("val0="+iref1
);// 10
//
// // get val
from array list
// int iref2 =
it.next();
// System.out.println("val1="+iref2);//
20
//
// // get val
from array list
// int iref3 =
it.next();
// System.out.println("val1="+iref3);//
// System.out.println("val2=");//
30
//
get val from array list
// int val4 =
it.next();
// System.out.println("val3="+
val3);// Exception in thread "main" java.util.NoSuchElementException
// at
java.base/java.util.ArrayList$Itr.next(ArrayList.java:970)
//
get all values from array list using iterator - and while loop
// true
while(it.hasNext())
{
int
ival =it.next();
System.out.println("get
all values using iterator Method="+ ival);
}
//
}
}
o/p:
Al =[10, 20, 30]
get all values using iterator
Method=10
get all values using iterator Method=20
get all values using iterator
Method=30
·
Iterator - Predefined interface and it has some
methods, can be used to iterate values from colllection obj
4.
ListIterator() :
ListIterator()- to iterate the values in forward direction
and in reverse direction
package CollectionFrameBasics;
import java.util.ArrayList;
import java.util.ListIterator;
public class
ListItertaorMethodToGetValuesFromArrayList {
public
static void main(String[] args) {
//
Create array List of String
ArrayList<String> al =
new ArrayList<String>();
al.add("Ram");
al.add("sita");
al.add("Raju");
//get
values from array list
// 4 ways
//
ListIterator ()
// al.iterator();
ListIterator<String>
lit = al.listIterator();
//
to iterate values in forward direction and also in reverse direction
// to get values from array list in forward
direction
while(lit.hasNext())
{
String
val = lit.next();
System.out.println("get
values from array list using listiterator in formward direction="+val);
}
// hasPrevious()
// previous()
//// to get values from array list in reverse
direction
System.out.println("Testing
***********");
while(lit.hasPrevious())
{
String
val = lit.previous();
System.out.println("get
values from array list using listiterator in Reverse direction="+val);
}
//
Note:
//
iterator() - to iterate the values in forward direction
only
// ex it.hasNext() , it.Next()
//
ListIterator()- to iterate the values in
forward direction and in reverse direction
//ex: lit.hasNext() ,
lit.Next()
// lit.hasPrevious() , lit.previous()
}
}
o/p:
get values from array list using
listiterator in formward direction=Ram
get values from array list using
listiterator in formward direction=sita
get values from array list using
listiterator in formward direction=Raju
Testing ***********
get values from array list using
listiterator in Reverse direction=Raju
get values from array list using
listiterator in Reverse direction=sita
get values from array list using
listiterator in Reverse direction=Ram
HW add float values into array list and
use all the method and get all
values from array list using above 4 ways?
HW add char values into array list' and
use all the method and get all
values from array list using above 4 ways?
No comments:
Post a Comment