0% found this document useful (0 votes)
25 views28 pages

Collections Day 2

Uploaded by

yevitoy306
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views28 pages

Collections Day 2

Uploaded by

yevitoy306
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

COLLECTIONS

(An easy way to manage


Objects)
Collection V/s Collections
• For beginners there is a point of confusion regarding the
terms Collection and Collections

• Collection in java is an interface available in the package


java.util and it acts as the super interface for all collection
classes like ArrayList , LinkedList , HashSet etc

• Collections is a class in the package java.util which contains


various static methods for performing utility operations on
collection classes .

• Some of it’s popular methods are sort( ),copy( ),


binarySearch( ) etc
Quiz
1. The core collection interfaces are organized into two
distinct inheritance trees. One interface in particular is
not a part of Collection, and therefore sits at the top of
its own tree. What is the name of this interface?

Answer: Map
Quiz
2. What interface represents a collection that does not
allow duplicate elements?

Answer: Set

3 Which class forms the root of the collections hierarchy?

Answer: None
Quiz
4. What interface forms the root of the collections
hierarchy?

Answer: Collection

5. What interface represents an ordered collection that


may contain duplicate elements?

Answer: List
Quiz
6. What interface represents a collection that holds
elements to be processed in FIFO order?

Answer: Queue

7. What is the difference between Collection and


Collections ?

Answer: First is an interface while second is a class


Quiz
8. Difference between HashSet and TreeSet
Answer:

HashSet TreeSet
Maintains elements in Maintains elements in
random order sorted order
Backed by HashMap Backed by binary tree

Faster Slower

Less functionality Rich in functionality


Quiz
9. In an e-commerce application which collection would
you use if you needed to maintain and search on orders
identified by their unique order-id ?

Answer: Map
The List Interface
• The java.util.List interface is a subtype of the
java.util.Collection interface and represents an
ordered collection (sometimes called a sequence).

• It means we can access the elements of a List in a


specific order, and by an index too.

• It allows duplicate objects.

• Each element is inserted and accessed in the list using


it’s index
Implementation Classes Of “List”
We can choose between the following List implementations
in the Java Collections API:

java.util.ArrayList

java.util.LinkedList

java.util.Vector

java.util.Stack
The “ArrayList” class
1. ArrayList implements the List interface

2. ArrayList capacity grows automatically.

3. It allows duplicate elements

4. Insertion order is preserved in the ArrayList

5. ArrayList is created with an initial size of 10 , although


we can change it’s initial capacity
Creating The “ArrayList” Object
• ArrayList can be created in 2 ways:

• Type UnSafe

AND

• Type Safe
Type UnSafe ArrayList
• Type UnSafe ArrayList can be created as shown below

• ArrayList obj=new ArrayList( );

• Although they are easier to create but we cannot check what kind of
data we are adding in the ArrayList.

• For ex:
obj.add(“Amit”);
obj.add(25);
obj.add(true);

• All the above lines will successfully compile and run.


Why Java Does Not Recommend To Use Type
UnSafe ArrayList ?

• This is because a type-unsafe ArrayList has 2 issues:

• ArrayList obj=new ArrayList( );


obj.add(“Amit”);
obj.add(25);
obj.add(true);

• 1. While getting back the values from the ArrayList we must be


sure about the type of data it is holding , otherwise code will
give error:

• int x=obj.get(0);// Syntax error


Why Java Does Not Recommend To Use Type
UnSafe ArrayList ?

• 2. Since the get() method has the return type of Object we


must use proper type-conversion ( downcasting) while
receiving the value:

• String x=obj.get(0);// Syntax error


• String x=(String)obj.get(0);// Correct
Type Safe ArrayList
• Type Safe ArrayList can be created as shown below

ArrayList<String> obj=new ArrayList<String>( );

• The < > is called diamond operator in Java and was introduced from Java 7
onwards .

• It tells the compiler to only allow programmer to add String values in the
ArrayList.

• Any other type of value cannot be added in the ArrayList and if we try to do so ,
the compiler will generate syntax error

• For ex:
obj.add(“Amit”); // Correct
obj.add(25); // Wrong
obj.add(true); // Wrong
Inserting Elements In ArrayList
• To insert an element in the ArrayList , we have to call the
method add( )

• This method has 2 versions:

• Prototype:

• public boolean add(Object)


• public void add(int , Object)

• The first method accepts an Object as argument and adds


that Object at the end of the ArrayList
Inserting Elements In ArrayList
• The second method accepts an index number as well as
an Object as argument and adds the Object at the
specified index

• If index is out of range then it throws the exception


IndexOutOfBoundsException

• For Ex:
ArrayList <String> cities = new ArrayList<>();
cities.add(“Bhopal”);
cities.add(0, “Indore”);
Retrieving Elements Of ArrayList
To retrieve an element from the ArrayList , we have to
call the method get( )

Prototype:
public Object get(int index)

This method accepts an index number as argument and


returns the element at that position

If index is out of range then it throws the exception


IndexOutOfBoundsException
Retrieving Elements Of ArrayList
For Ex:

String s=cities.get(0);
String p=cities.get(1);
System.out.println(s); // will show Indore
System.out.println(p); // will show Bhopal
Checking size of ArrayList
• Size of an ArrayList means total number of elements currently
present in it.

• To retrieve size of an ArrayList , we have a method called size()


whose protoype is:

• public int size( )

For Ex:

int n = cities.size();
Exercise 1
• WAP to store names of first four months in the
ArrayList and then print them back .
Retrieving Item From ArrayList Using
Enhanced for
We can traverse an ArrayList also using enhanced
for loop

Using Enhanced For loop

for(String item: cities){


System.out.println("retrieved element: " + item);
}
Searching An Element In ArrayList
Sometimes we need to check whether an element exists
in ArrayList or not.

For this purpose we can use contains () method of Java.


contains() method takes type of object defined in the
ArrayList creation and returns true if this list contains the
specified element.

For Ex:
boolean found=cities.contains(“Bhopal”);
Another Way Of Searching An Element In
ArrayList
We also can use indexOf() method of ArrayList in Java to
find out index of a particular object.

int index = cities.indexOf(“Bhopal”);


Exercise 2
• According to IMDB following are top earning Bollywood movies
of the year 2023, till now:
• 1-Pathaan
2-Gadar-2
3-The Kerala Story
4-Adipurush
5-TJMM

WAP to do the following:


1. Accept names of these 5 movies and store them in the
ArrayList

2. Now ask the user to input a movie name and search and print
it’s ranking. If the movie is not found then print the message
Movie not found
Removing an Item from ArrayList
• There are two ways to remove any element from
ArrayList in Java.
• The method to be called is remove( )
• This method has 2 versions:
• Prototype:
• public boolean remove(Object)
• public Object remove(int)

• We can either remove an element based on its index or


by providing object itself.
• cities.remove(0);
cities.remove(“Indore”);
Exercise 3
• WAP to do the following

1. Accept names of 5 fruits from the user .

2. Then ask the user to input a fruit name and remove it


from the list .

3. Now print the modified list and if the fruit name is not
found then print the message Fruit not found

You might also like