0% found this document useful (0 votes)
10 views52 pages

Chapter One-Javacollections

The document provides an overview of the Java Collections Framework, detailing its main types: Lists, Sets, and Maps, along with their characteristics and methods. It explains how collections store objects, the operations available through the Collection interface, and the use of iterators for accessing elements. Additionally, it covers specific implementations like ArrayList, LinkedList, and HashSet, including examples of their usage in Java programming.

Uploaded by

abay.b242
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)
10 views52 pages

Chapter One-Javacollections

The document provides an overview of the Java Collections Framework, detailing its main types: Lists, Sets, and Maps, along with their characteristics and methods. It explains how collections store objects, the operations available through the Collection interface, and the use of iterators for accessing elements. Additionally, it covers specific implementations like ArrayList, LinkedList, and HashSet, including examples of their usage in Java programming.

Uploaded by

abay.b242
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/ 52

Chapter - one

Java Collection Framework

1
Chapter Topics

o Introduction to the Java collections Framework


o Lists
o Sets
o Maps

04/23/2025 2 2
Introduction to the Java collections Framework
The Java Collections Framework is a library of
classes and interfaces for working with collections
of objects.

A collection is an object which can store other


objects, called elements. Collections provide
methods for adding and removing elements, and for
searching for a particular element within the
collection.

04/23/2025 3 3
The Main Types of Collections

•Lists
•Sets
•Map
s

04/23/2025 4 4
Lists

Lists: List type collections assign an integer (called an


index) to each element stored.
Indices of elements are 0 for the element at the
beginning of the list, 1 for the next element, and so
on.
Lists permit duplicate elements, which are
distinguished by their position in the list.

04/23/2025 5 5
Sets

Set: a collection with no notion of position within the


collection for stored elements. Sets do not permit
duplicate elements.

6
Map
s

A map is a collection of pairs of objects:


1. A value: this is the object to be stored.
2. A key: this is another object associated with the value, and which can be
used to quickly find the value within the collection.
A map is really a set of keys, with each each key
having a value attached to it.
Maps do not allow duplicate keys.

04/23/2025 7 7
04/23/2025 8 8
The Collection
Interface

•Lists and Sets are similar in many ways.


•The Collection Interface describes the operations that
are common to both.
•Maps are fundamentally different from Lists and Sets
and are described by a different interface.

04/23/2025 9 9
Some Methods in the Collection Interface
Method Description
add(o : E) : boolean Adds an object o to the Collection. The method
returns true if o is successfully added to the
collection, false otherwise.
clear() : void Removes all elements from the collection.

contains(o : Returns true if o is an element of the


Object): boolean collection, false otherwise.
isEmpty() : boolean Returns true if there are no elements in the
collection,
false otherwise.
iterator() : Returns an object called an iterator that can be
Iterator<E> used to examine all elements stored in the
collection.
remove(o : Removes the object o from the collection and
Object) : returns true if the operation is successful,
boolean false otherwise.
size() : int Returns the number of elements currently
04/23/2025
stored in the collection. 1 10
0
AbstractCollection

The AbstractCollection class provides a skeleton


implementation for a Collection class by
implementing many of the methods of the
Collection interface.

Programmers can create a working collection class


by providing implementations for iterator(), size(),
and overriding add(o : Object).

04/23/2025 1 11
1
Iterators

An iterator is an object that is associated with a


collection. The iterator provides methods for
fetching the elements of the collection, one at a
time, in some order.

04/23/2025 1 12
2
The Iterator Interface

Iterators implement the Iterator interface. This


interface specifies the following methods:
hasNext() : boolean
next() : E
remove() : void
The remove() method is optional, so not all
iterators have it.

04/23/2025 1 13
3
The List
Interface

The List interface extends the Collection interface by


adding operations that are specific to the position-based,
index-oriented nature of a list.

Can be implemented with array list class & linked list


classes

1
4
List Interface
Methods

•The methods in the List interface describe


operations for adding elements and removing
elements from the list based on the index of the
element.
•There are also methods for determining the
index of an element in the list when the value of
an element is known.

04/23/2025 1 15
5
The List Interface
Methods
add(index:int,el:E) Adds the element el to the collection at the given
: void index. Throws IndexOutOfBoundsException if
index is negative, or greater than the size of the
list.
get(index:int):E Returns the element at the given index, or throws
IndexOutBoundsException if index is negative or
greater than or equal to the size of the list.
indexOf(o:Object):int Returns the least (first) index at which the
object o is found; returns -1 if o is not in the
list.
lastIndexOf(o:Object):i Returns the greatest (last) index at which the
nt object o is found; returns -1 if o is not in the list.
listIterator():ListItera Returns an iterator specialized to work
tor< E> with List collections.
remove(index:int):E Removes and returns the element at the given
index; throws IndexOutOfBoundsException if
index is negative, or greater than or equal to the
size of the list.
04/23/2025
set(index:int, el:E):E Replaces the element at index with the new 16 16
Other List Interface Method
o Add(index/value);
o addAll(collection c);
o Remove(object/index);
o RemoveAll(collection c);
o Get(index/value);
o Set(index,new value)
o Contains(object)
o isEmpty();
o Size();
04/23/2025 17
ArrayList and Vector

ArrayList and Vector are array-based lists.


Internally, they use arrays to store their elements:
whenever the array gets full, a new, bigger array is
created, and the elements are copied to the
new array.

Vector has higher overhead than ArrayList because


Vector is synchronized to make it safe for use in
programs with multiple threads.

04/23/2025 1 18
8
AbstractSequentialList and LinkedList

Array-based lists have high overhead when elements are


being inserted into the list, or removed from the list, at
positions that are not at the end of the list.

LinkedList is a concrete class that stores elements in a way


that eliminates the high overhead of adding to, and
removing from positions in the middle of the list.

LinkedList extends AbstractSequentialList, which in turn,


extends AbstractList.

04/23/2025 1 19
9
Example:
ArrayList
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
List<String> nameList = new ArrayList<String> ();
String [ ] names = {"Ann", "Bob", "Carol"};

// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);

// Display name list


for (int k = 0; k < nameList.size(); k++)
System.out.println(nameList.get(k));
}
}
04/23/2025 2 20
0
package javacolls; System.out.println("display array by using for
import java.util.*; loop");
for(int i=0;i<all.size();i++)
public class JavaColls { {
System.out.println(all.get(i));
}
public static void main(String[] args) {
System.out.println("display array by using for
ArrayList all=new ArrayList();
each loop");
all.add("x");
for( Object e:all)
all.add('h');
{
all.add("go"); System.out.println(e);
all.add("xoo"); }
all.add("baby"); System.out.println("display arry by using
all.add("gaga"); ITERATORS");
System.out.println("array holds"+all); Iterator it=all.iterator();
all.set(2,"tiktoke"); while(it.hasNext())
System.out.println("array after set"+all); {
System.out.println(all.contains("xoo")); System.out.println(it.next());
}
ut put
System.out.println(all.size());
all.remove("xoo"); } Get o
System.out.println("after removing xoo"+all);
System.out.println(all.get(2)); }
04/23/2025 21
An Example: LinkedList

Because we used a List reference to refer to the


concrete class objects, we can easily switch from an
ArrayList to a LinkedList : the only change is in the
class used to instantiate the collection.

04/23/2025 2 22
2
Example:
LinkedList
import java.util.*;
public class Test
{
public static void main(String [ ] args)
{
List<String> nameList = new LinkedList<String> ();
String [ ] names = {"Ann", "Bob", "Carol"};

// Add to arrayList
for (int k = 0; k < names.length; k++)
nameList.add(names[k]);

// Display name list


for (int k = 0; k < nameList.size(); k++)
System.out.println(nameList.get(k));
}
}
04/23/2025 2 23
3
Class work 2
get the output of the java code below
LinkedList con=new LinkedList();
String[] arr= {"people","animal","plant","bird"};
//element added to LL
for(int i=0;i<arr.length;i++)
con.add(arr[i]);
System.out.println("print content of ll");
for(int j=0;j<con.size();j++)
System.out.println(con.get(j));
//remove object people from ll
con.remove("people");
System.out.println("second output");
System.out.println(con);
con.set(0,"repitailes");
con.set(1,"repitailes");
System.out.println("third output");
System.out.println(con);
System.out.println("fourth output");
System.out.println(con.get(2));
04/23/2025 24
Using an Iterator

To use an iterator with a collection,


1. Call the iterator():Iterator<E> method of the collection to retrieve an
iterator object.
2. Use the hasNext():boolean method to see if there still remain elements to
be returned, and the next():E method to return the next available element.

04/23/2025 2 25
5
Example Use of Iterator
public static void main(String [ ] args)
{
List<String> nameList = new ArrayList<String>();
String [ ] names = {"Ann", "Bob", "Carol"};

// Add to arrayList using a ListIterator ListIterator<String> it =


nameList.listIterator(); for (int k = 0; k < names.length; k++)
it.add(names[k]);
while (it.hasNext())
System.out.println(it.next());
}

04/23/2025 26
Class work 3
Get the out put of the code below?
public static void main(String[] args) {
System.out.println("well come to second java project");
LinkedList ll=new LinkedList();//declaring linked list
Integer [] a={1,2,4,5,6,7};
//adding element to linked list using for loop

for(int i=0;i<a.length;i++)
ll.add(a[i]);
//print elements of linked list
for(int j=0;j<ll.size();j++)
System.out.println("iteration \t\t"+(j+1)+"\t"+ll.get(j));
04/23/2025 27
Sets

Sets are collections that store elements, but have


no notion of a position of an element within the
collection.

The distinguishing feature of a set as a collection is


that it does not allow duplicates.

04/23/2025 28
The Set Part of the JCF
Hierarchy
AbstractCollecti
on

AbstractS
et

HashSe TreeSe
t t

LinkedHashS
et

04/23/2025 29
The Set Part of the
JCF

AbstractSet implements the Set Interface.

TreeSet implements the SortedSet interface, which


has methods for working with elements that have
an order that allows them to be sorted according to
their value.

04/23/2025 30
HashSet

•HashSets store elements according to a hash code.


•A hash code of an element is an integer computed
from the value of the element that can be used to
help identify the element.
•The procedure used to compute the hash code of
an element is called the hashing function or the
hashing algorithm.

04/23/2025 31
Examples of Hashing
Functions
•For Integer objects, you can use the integer value of
the object (or its absolute value).

•For Character objects, you can use the UNICODE value


for the character.

•For String objects, you can use a function that takes


into account the UNICODE values of the characters
that make up the string, as well as the position
occupied by each character.

04/23/2025 32
HashSet Capacity and Load Factor

•The load factor of a HashSet is the fraction of buckets


that must be occupied before the number of buckets
is increased.
•The number of buckets in a HashSet is called its
capacity.

04/23/2025 33
Some HashSet
Constructors

HashSet() Creates an empty HashSet object


with a default initial capacity of 16
and load factor of 0.75.
HashSet(int Creates an empty HashSet object
initCapacity, float with the specified initial capacity
loadFactor) and load factor.
HashSet(int Creates an empty HashSet object with
initCapacity) the specified initial capacity and a
load factor of 0.75.

04/23/2025 34
HashSet Example 1
// Create a HashSet to hold String objects.
Set<String> fruitSet = new HashSet<String>();

// Add some strings to the set.


fruitSet.add("Apple");
fruitSet.add("Banana");
fruitSet.add("Pear");
fruitSet.add("Strawberry");
// Display the elements in the set.
System.out.println("Here are the elements.");
for (String element : fruitSet)
System.out.println(element);
// Try to add a duplicate element.
System.out.println("\nTrying to add Banana to " +
"the set again...");
if (!fruitSet.add("Banana"))
System.out.println("Banana was not added again.");
// Display the elements in the set.
System.out.println("\nHere are the elements once more.");
for (String element : fruitSet)
04/23/2025 35
get the output
HashSet hs=new HashSet();
String[] arr= {"lion","tiger","cat","rabit"};
for(int i=0;i<arr.length;i++)
hs.add(arr[i]);
//print the element on screen
System.out.println(hs);
System.out.println(hs.contains("tiger"));
HashSet ss=new HashSet();
ss.addAll(hs);
ss.add("giraff");
System.out.println(ss);
ss.removeAll(hs);
System.out.println(ss);

04/23/2025 36
get the output
HashSet set=new HashSet();
Integer[] arr= {1,2,3,4,5,6};
for(int i=0;i<arr.length;i++)
set.add(arr[i]);

HashSet set2= new HashSet();


Integer[] array= {2,3,4,7,8,9};
for(int j=0;j<array.length;j++)
set2.add(array[j]);
System.out.println(set);
set.addAll(set2);
System.out.println(set);
set.removeAll(set2);
System.out.println(set);
04/23/2025 37
HashSet Example 2
import java.util.*;
/**
This program creates a HashSet, adds some
names to it, gets an iterator for the set,
and searches the set for names.
*/
public class HashSetDemo2
{
public static void main(String[] args)
{
// Create a HashSet to hold names.
Set<String> nameSet = new HashSet<String>();
// Add some names to the set.
nameSet.add("Chris");
nameSet.add("David");
nameSet.add("Katherine");
nameSet.add("Kenny");
// Get an iterator for the set.
Iterator it =
nameSet.iterator();

04/23/2025 38
HashSet Example 2
// Display the elements in the set.
System.out.println("Here are the names in the set.");
while (it.hasNext())
System.out.println(it.next());
System.out.println();
// Search for "Katherine". We should find this
// name in the set.
if (nameSet.contains("Katherine"))
System.out.println("Katherine is in the set.");
else
System.out.println("Katherine is NOT in the
set.");
// Search for "Bethany". We should not find
// this name in the set.
if (nameSet.contains("Bethany"))
System.out.println("Bethany is in the set.");
else
} System.out.println("Bethany is NOT in the
} set.");

04/23/2025 39
LinkedHashSet

A linkedHashSet is just a HashSet that keeps track of


the order in which elements are added using an
auxiliary linked list.
TreeSe
t
A TreeSet stores elements based on a natural order
defined on those elements.

The natural order is based on the values of the


objects being stored .

By internally organizing the storage of its elements


according to this order, a TreeSet allows fast search for
any element in the collection.

04/23/2025 41
Sorting Strings Using a TreeSet
import java.util.*;
public class Test
{
public static
void
main(String [ ]
args)
{
// Create
TreeSet
Set<String>
mySet = new
TreeSet<Strin
g>();
// Add Strings
mySet.add("Alan");
mySet.add("Carol")
;
mySet.add("Bob");
// Get Iterator
Iterator it = mySet.iterator();
04/23/2025 42
Using a TreeSet to Sort Strings in
Reverse Alphabetic Order
public class Test
{
public static void main(String [ ] args)
{ // Create Comparator
RevStrComparator comp = new RevStrComparator();
Set<String> mySet = new TreeSet<String>(comp);
// Add strings
mySet.add("Alan");
mySet.add("Carol")
;
mySet.add("Bob");
// Get Iterator
Iterator it = mySet.iterator();
while (it.hasNext())
{
System.out.println(it.next(
));
}
}
}
04/23/2025 43
TreeSet Example 1
public static void main(String[] args)
{
// Create a TreeSet and store some values in it.
SortedSet<String> mySet = new TreeSet<String>();
mySet.add("Pear");
mySet.add("Apple");
mySet.add("Strawberry"); mySet.add("Banana");
System.out.println("Here are the TreeSet elements " +
"in ascending order:");
for (String str : mySet)
System.out.println(str);

System.out.println("\nAdding Blueberry to the set."); mySet.add("Blueberry");


System.out.println("\nHere are the TreeSet elements " +
"again:");

for (String str : mySet)


System.out.println(str);
} }
04/23/2025
44
Maps
A map is a collection whose elements have two parts: a key
and a value.

The combination of a key and a value is called a mapping.

The map stores the mappings based on the key part of the
mapping, in a way similar to how a Set collection stores its
elements.

The map uses keys to quickly locate associated values.

04/23/2025 45
The Map Part of the JCF
Hierarchy
Ma
p

AbstractMa
p

HashMa TreeMa
p p

LinkedHashMa
p

04/23/2025 46
The Map
Interface

Map is a generic interface Map<K, V>

Map specifies two type parameters, K for the key,


and V for the value part of the mapping.

04/23/2025 47
Some Methods of the
Map Interface
clear() : void Removes all elements from the map.

containsValue(val Returns true if the map contains a


ue: mapping with the given value.
Object):boolean
containsKey(key : Returns true if the map contains a mapping
Object) with
: boolean the given key.
get(key : Object) : V Returns the value associated with the
specified key, or returns null if there is
no such value.
isEmpty() : boolean Returns true if the key contains no mappings.

keySet() : Set<K> Returns the set of all keys stored in the map.

04/23/2025 48
Some Methods of the Map
Interface

put(key : K, value : V) : Adds a mapping that associates V with K, and


V returns the value previously associated with
K. Returns null if there was no value
associated with K.
remove(key : Object) : Removes the mapping associated with the
V given key from the map, and returns the
associated value. If there is not such
mapping, returns null.
size() : int Returns the number of mappings in the map.

values() : Returns a collection consisting of all values


Collection<V> stored in the map.

04/23/2025 49
Concrete Map
Classes
Maps store keys with attached values. The keys are
stored as sets.
•HashMap stores keys according to their hash codes, just like
HashSet stores its elements.
•LinkedHashMap is a HashMap that can iterate over the keys
in insertion order (order in which mappings were inserted)
or in access order (order of last access).
•TreeMap stores mappings according to the natural order of
the keys, or according to an order specified by a
Comparator.

04/23/2025 50
Get the output
Hashtable<Integer,String> ht=new
Hashtable<Integer,String>();
ht.put(1,"kebede");
ht.put(2, "abebe");
ht.put(3,"ayele");
System.out.print(ht);
System.out.println(ht.keySet());
System.out.println(ht.values());
ht.remove(2);
System.out.println(ht);
04/23/2025 51
n e
r o
p te A
h a
c ??Q &
o f ?
d ?
En ? ? ? ?
?

04/23/2025 52

You might also like