COLLECTIONS java
COLLECTIONS java
Answer: Map
Quiz
2. Which interface represents a collection that does not
allow duplicate elements?
Answer: Set
Answer: None
Quiz
4. Which interface forms the root of the collections
hierarchy?
Answer: Collection
Quiz
5. Which interface represents an ordered collection that
may contain duplicate elements?
Answer: List
Answer: Queue
Quiz
HashSet TreeSet
Maintains elements in Maintains elements in
random order sorted order
Backed by Hashtable Backed by binary search
tree
Faster Slower
1. java.util.Map
2. java.util.Set
3. java.util.List
4. java.util.Collection
Answer: java.util.Set
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).
java.util.ArrayList
java.util.LinkedList
java.util.Vector
java.util.Stack
The “ArrayList” class
1. ArrayList implements the List interface
• Type UnSafe
AND
• Type Safe
Type UnSafe ArrayList
• Type UnSafe ArrayList can be created as shown below
• 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);
• The < > are called diamond operator in Java and they tell the
compiler to only allow us to add String values in the ArrayList.
• 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( )
• Prototype:
• 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)
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.
For Ex:
int n = cities.size();
Exercise 1
• WAP to store names of first four months in the ArrayList
and them print them back .
Retrieving Item From ArrayList Using
Enhanced for
We can traverse an ArrayList also using enhanced
for loop
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.
3. Now print the modified list and if the fruit name is not
found then print the message Fruit not found