You are on page 1of 36

Collections & Exceptions

WWW.PENTALOG.COM
Course goals:
- Base knowledge of collections and other data types
- Basic knowledge of java exceptions
- Practical examples of writing and running base java programs

WWW.PENTALOG.COM
Recap interfaces / Nested classes

Nested classes
https://www.tutorialspoint.com/java/java_innerclasses.htm
https://www.baeldung.com/java-nested-classes
https://dzone.com/articles/nested-classes-in-java

Interfaces
https://www.tutorialspoint.com/java/java_interfaces.htm
https://www.geeksforgeeks.org/interfaces-in-java/
https://www.javatpoint.com/interface-in-java

WWW.PENTALOG.COM
Collections in java

A Collection is a group of individual objects


represented as a single unit. Java provides
Collection Framework which defines several
classes and interfaces to represent a group of
objects as a single unit.

Java Collections can achieve all the operations


that you perform on a data such as

● searching
● sorting
● insertion
● manipulation
● deletion

WWW.PENTALOG.COM
5

WWW.PENTALOG.COM
add addAll remove ... removeAll size contains

WWW.PENTALOG.COM
7

WWW.PENTALOG.COM
8

WWW.PENTALOG.COM
List interface

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

List <Object> list1 = new ArrayList<>();


List <Object> list2 = new LinkedList<>();
List <Object> list3 = new Vector<>();
List <Object> list4 = new Stack<>();

WWW.PENTALOG.COM
List interface - Iterator

Iterator

ListIterator

10

WWW.PENTALOG.COM
List interface - Iterator
Often, you will want to cycle through the elements in a collection. For example, you might want to
display each element. The easiest way to do this is to employ an iterator, which is an object that
implements either the Iterator or the ListIterator interface

In general, to use an iterator to cycle through the contents of a collection, follow


these steps −

● Obtain an iterator to the start of the collection by calling the collection's

iterator( ) method.

● Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as

hasNext( ) returns true.

● Within the loop, obtain each element by calling next( ).

11

WWW.PENTALOG.COM
List interface - ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of different
data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements stored in the
ArrayList class can be randomly accessed

// Initialize list
ArrayList<String> list=new ArrayList<>();

// Add elements
list.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 4");

// get elements
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

12

WWW.PENTALOG.COM
List interface - LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It can store
the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the manipulation is fast
because no shifting is required.

// Initialize list
LinkedList<String> list=new LinkedList<>();

// Add elements
list.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 4");

// get elements
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

13

WWW.PENTALOG.COM
List interface - Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and
contains many methods that are not the part of Collection framework.

// Initialize list
Vector<String> list=new Vector<>();

// Add elements
list.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 4");

// get elements
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

14

WWW.PENTALOG.COM
List interface - Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all
of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object
o), which defines its properties.

// Initialize list
Stack<String> list=new Stack<>();

// Add elements
list.push("element 1");
list.push("element 2");
list.push("element 3");
list.push("element 4");

// get elements
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

15

WWW.PENTALOG.COM
Set interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered
set of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is
implemented by HashSet, LinkedHashSet, and TreeSet.

Set<Object> set1 = new HashSet<>();


Set<Object> set2 = new LinkedHashSet<>();
Set<Object> set3 = new TreeSet<>();

16

WWW.PENTALOG.COM
Set interface - HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is
used to store the elements in the HashSet. It contains unique items.

// Initialize list
Set<String> list=new HashSet<>();

// Add elements
list.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 4");

// get elements
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

17

WWW.PENTALOG.COM
Set interface - LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and
implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits
null elements.

// Initialize list
Set<String> list=new LinkedHashSet<>();

// Add elements
list.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 4");

// get elements
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

18

WWW.PENTALOG.COM
(Sorted)Set interface - TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains
unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in
ascending order

// Initialize list
Set<String> list=new TreeSet<>();

// Add elements
list.add("element 1");
list.add("element 2");
list.add("element 3");
list.add("element 4");

// get elements
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

19

WWW.PENTALOG.COM
Collections - Read more
https://www.tutorialspoint.com/java/java_collections.htm
https://www.geeksforgeeks.org/collections-in-java-2/
https://www.javatpoint.com/collections-in-java
https://beginnersbook.com/2013/12/java-arraylist/
https://www.geeksforgeeks.org/arraylist-in-java/
https://www.tutorialspoint.com/java/java_using_iterator.htm

20

WWW.PENTALOG.COM
Map interface
The Map interface maps unique keys to values. A key is an object that you use to retrieve a value
at a later date.

21

WWW.PENTALOG.COM
Map interface - HashMap
Java HashMap class implements the map interface by using a hash table. It inherits AbstractMap class and implements
Map interface.

● Java HashMap class contains values based on the key.


● Java HashMap class contains only unique keys.
● Java HashMap class may have one null key and multiple null values.
● Java HashMap class is non synchronized.
● Java HashMap class maintains no order.
● The initial default capacity of Java HashMap class is 16 with a load factor of 0.75

Map<String, String> map = new HashMap<>();

map.put("key 1", "element1");


map.put("key 2", "element2");
map.put("key 3", "element3");
map.put("key 4", "element4");
map.put("key 5", "element5");

for (Map.Entry entry : map.entrySet()) {


System.out.println(entry.getKey() + ":" + entry.getValue());
}

22

WWW.PENTALOG.COM
Map interface - LinkedHashMap
Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface, with predictable iteration
order. It inherits HashMap class and implements the Map interface.

● Java LinkedHashMap contains values based on the key.


● Java LinkedHashMap contains unique elements.
● Java LinkedHashMap may have one null key and multiple null values.
● Java LinkedHashMap is non synchronized.
● Java LinkedHashMap maintains insertion order.
● The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Map<String, String> map = new LinkedHashMap<>();

map.put("key 1", "element1");


map.put("key 2", "element2");
map.put("key 3", "element3");
map.put("key 4", "element4");
map.put("key 5", "element5");

for (Map.Entry entry : map.entrySet()) {


System.out.println(entry.getKey() + ":" + entry.getValue());
}

23

WWW.PENTALOG.COM
Map interface - TreeMap
Java TreeMap class is a red-black tree based implementation. It provides an efficient means of storing key-value pairs
in sorted order.

● Java TreeMap contains values based on the key. It implements the NavigableMap interface and extends
AbstractMap class.
● Java TreeMap contains only unique elements.
● Java TreeMap cannot have a null key but can have multiple null values.
● Java TreeMap is non synchronized.
● Java TreeMap maintains ascending order.

Map<String, String> map = new TreeMap<>();

map.put("key 1", "element1");


map.put("key 2", "element2");
map.put("key 3", "element3");
map.put("key 4", "element4");
map.put("key 5", "element5");

for (Map.Entry entry : map.entrySet()) {


System.out.println(entry.getKey() + ":" + entry.getValue());
}

24

WWW.PENTALOG.COM
Map interface - Read more

https://www.baeldung.com/java-hashmap

https://www.quora.com/How-is-Hashmap-in-Java-implemented-internally-What-are-the-pros-and-cons-to-use-it-Wha
t-are-the-complexities-it-provides-for-insert-delete-and-lookup

https://www.geeksforgeeks.org/internal-working-of-hashmap-java/

http://tutorials.jenkov.com/java-collections/map.html

https://www.codejava.net/java-core/collections/java-map-collection-tutorial-and-examples

25

WWW.PENTALOG.COM
Java Enums
A Java Enum is a special Java type used to define collections of constants. More precisely, a Java enum type is a
special kind of Java class. An enum can contain constants, methods etc. Java enums were added in Java.

Because they are constants, the names of an enum type's fields are in uppercase letters

Constants defined this way make the code more readable, allow compile-time checking, document upfront the list of
accepted values and avoid unexpected behavior due to invalid values being passed in.

public enum Level {


HIGH,
MEDIUM,
LOW
}

https://www.baeldung.com/a-guide-to-java-enums
http://tutorials.jenkov.com/java/enums.html
https://dzone.com/articles/using-java-enums

26

WWW.PENTALOG.COM
Exceptions in java

An exception (or exceptional event) is a problem


that arises during the execution of a program.
When an Exception occurs the normal flow of the
program is disrupted and the program/Application
terminates abnormally, which is not
recommended, therefore, these exceptions are to
be handled

In java, we have 3 categories of exceptions

- Checked exceptions
- Unchecked exceptions
- Errors

27

WWW.PENTALOG.COM
Exceptions in java

Checked exceptions - A checked exception is an exception that is checked (notified) by the compiler
at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply
be ignored, the programmer should take care of (handle) these exceptions.

Unchecked exceptions - An unchecked exception is an exception that occurs at the time of


execution. These are also called as Runtime Exceptions. These include programming bugs, such as
logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.

Errors - These are problems that arise beyond the control of the user or the programmer. Errors are
typically ignored in your code because you can rarely do anything about an error. For example, if a
stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

28

WWW.PENTALOG.COM
Exceptions in java

29

WWW.PENTALOG.COM
Exceptions in java - Throwable

30

WWW.PENTALOG.COM
Exceptions in java - Throwing exceptions

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We
can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom
exceptions. All thrown exceptions must be of type Throwable

throw new IllegalAccessException("Exception message")

The throws keyword in Java is used to explicitly state that a method is throwing an exception. This is
required for all thrown checked exceptions.

public void calculateAmount() throws IllegalAccessException {


throw new IllegalAccessException("demo");
}

When using methods that throws checked exceptions, we are forced to either handle the exception
within a try/catch block, or mark our method as well with throws keyword

31

WWW.PENTALOG.COM
Exceptions in java - Catching exceptions

A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following

try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}

Catch multiple exceptions

try { try {
// Protected code // Protected code
} catch (ExceptionType1 e1) { } catch (ExceptionType1 e1) {
// Catch block // Catch block
} catch (ExceptionType2 e2) { } catch (ExceptionType2 e2) {
// Catch block // Catch block
} catch (ExceptionType3 e3) { } catch (IOException|FileNotFoundException ex) {
// Catch block // Catch block
} }

32

WWW.PENTALOG.COM
Exceptions in java - Finally

The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of
occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter
what happens in the protected code.

try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}

33

WWW.PENTALOG.COM
Exceptions in java - Try with resources

Generally, when we use any resources like streams, connections, etc. we have to close them explicitly using
finally block. In the following program, we are reading data from a file using FileReader and we are closing it
using finally block

File file = new File("path/to/file");


try (Scanner scanner = new Scanner(file)) {

} catch (FileNotFoundException ex) {


throw ex;
}

34

WWW.PENTALOG.COM
Exceptions in java - Recap

● A catch clause cannot exist without a try statement.

● It is not compulsory to have finally clauses whenever a try/catch block is present.

● The try block cannot be present without either catch clause or finally clause.

● Any code cannot be present in between the try, catch, finally blocks.

● 3 types of exceptions. Checked. Unchecked and Errors

● All exceptions must be a child of Throwable.

● If you want to write a runtime exception, you need to extend the RuntimeException class.

35

WWW.PENTALOG.COM
36

WWW.PENTALOG.COM

You might also like