Advanced Programming in Java Containers Mehdi Einali 1

  • Slides: 66
Download presentation
Advanced Programming in Java Containers Mehdi Einali 1

Advanced Programming in Java Containers Mehdi Einali 1

2

2

agenda Containers Collection Set Map Linked. List Iterator 3

agenda Containers Collection Set Map Linked. List Iterator 3

lists 4

lists 4

array Suppose we have an array of students Student[] students = new Student[34]; What

array Suppose we have an array of students Student[] students = new Student[34]; What if we do not know the array size? A default initial size What if we want to add more students to array? Double the size of array Copy old elements What if we want to remove some students from array? Nullify the element & shift the others We need a dynamic array 5

Arrays is not enough Arrays are efficient, typed and can store primitive types Size

Arrays is not enough Arrays are efficient, typed and can store primitive types Size is fixed (can't grow or shrink) Arrays are useful when maximum number of objects can be guessed. For more general situations we need to use other form of containers like Lists, Sets and Maps 6

Array list Java introduces Collection classes for this purpose Array. List students = new

Array list Java introduces Collection classes for this purpose Array. List students = new Array. List(); students. add(new Student("Ali Alavi")); students. add(new Student("Taghi Taghavi")); students. remove(0); 7

Generic Array. List is also a generic type Array. List<Student> students = new Array.

Generic Array. List is also a generic type Array. List<Student> students = new Array. List<Student>(); students. add(new Student("Ali Alavi")); students. add(new Student("Taghi Taghavi")); students. remove(0); students. remove(new Student("Ali Alavi")); Student student = students. get(0); System. out. println(student); Array. List<T> implements generic interface List<T> 8

interface List<E>{ int size(); boolean is. Empty(); boolean contains(Object o); boolean add(E e); boolean

interface List<E>{ int size(); boolean is. Empty(); boolean contains(Object o); boolean add(E e); boolean remove(Object o); void clear(); E get(int index); E set(int index, E element); void add(int index, E element); E remove(int index); int index. Of(Object o); int last. Index. Of(Object o); List<E> sub. List(int from. Index, int to. Index); } 9

Array. List<String> list = new Array. List<String>(); Scanner scanner = new Scanner(System. in); while(true){

Array. List<String> list = new Array. List<String>(); Scanner scanner = new Scanner(System. in); while(true){ String input = scanner. next(); if(input. equals. Ignore. Case("exit")) break; list. add(input); } if(list. is. Empty()){ System. out. println("No string entered"); }else{ System. out. println("" + list. size() + " strings enetered"); if(list. contains("Ali")) System. out. println("Ali Found!"); for (String s : list) { System. out. println(s); For each is available for collections } 10 }

Array. List or Array? That is the question Do we need a dynamic array?

Array. List or Array? That is the question Do we need a dynamic array? Add Remove Performance issue Array. List is implemented using an array 11

Array to List Guess how? String[] strings = {"ali", "taghi"}; Array. List<String> list =

Array to List Guess how? String[] strings = {"ali", "taghi"}; Array. List<String> list = new Array. List<String>(); for (String string : strings) { list. add(string); } 12

List to Array Two methods: Object[] to. Array(); <T> T[] to. Array(T[] a); Array.

List to Array Two methods: Object[] to. Array(); <T> T[] to. Array(T[] a); Array. List<String> list = new Array. List<String>(); Object[] array = list. to. Array(); String[] array 2 = list. to. Array(new String[list. size()]); 13

Array. List<String> as; Array. List<Object> ao; List<Object> lo; List<String> ls; True/False? Array. List<String> is

Array. List<String> as; Array. List<Object> ao; List<Object> lo; List<String> ls; True/False? Array. List<String> is subclass of List<String> ls = as; Array. List<String> is subclass of Array. List<Object> ao = as; Array. List<String> is subclass of List<Object> lo=as; 14

Array list implementation In the heart of an Array. List, an array lives… public

Array list implementation In the heart of an Array. List, an array lives… public class Array. List<E>. . . , implements List<E>, . . . { private Object[] element. Data; private int size; public boolean add(E e) { ensure. Capacity(size + 1); element. Data[size++] = e; return true; } } 15

Collection is super-class of many containers public interface Collection<E> Some methods: int size(); boolean

Collection is super-class of many containers public interface Collection<E> Some methods: int size(); boolean is. Empty(); boolean contains(Object o); boolean add(E e); boolean remove(Object o); void clear(); Object[] to. Array(); <T> T[] to. Array(T[] a); 16

Linked. List and Array. List are both subclass of List Array. List is implemented

Linked. List and Array. List are both subclass of List Array. List is implemented by an array Linked. List is implemented by a doubly linked list It is used like an Array. List Because they are brothers! (subclass of List) 17

Linked List 18

Linked List 18

Doubly Linked List 19

Doubly Linked List 19

Linked. List Example List<String> list = new Linked. List<String>(); list. add("Ali"); list. add("Taghi"); System.

Linked. List Example List<String> list = new Linked. List<String>(); list. add("Ali"); list. add("Taghi"); System. out. println(list. get(0)); list. remove("Taghi"); for (String string : list) { System. out. println(string); } 20

Array. List vs. Linked. List stores two links for each element if you want

Array. List vs. Linked. List stores two links for each element if you want to do many insertions and removals in the middle of a list a Linked. List is better If not, an Array. List is typically faster 21

Array, Array. List and Linked. List 22

Array, Array. List and Linked. List 22

Linked. List<E> Array. List<E> get(int index) O(n) O(1) main benefit add(E element) O(1) [O(n)

Linked. List<E> Array. List<E> get(int index) O(n) O(1) main benefit add(E element) O(1) [O(n) worse case= add(int index, E element) O(n) resizing] O(n-index) [O(n) worse case= resizing] remove(int index) O(n-index) Iterator. remove() O(1) main benefit O(n-index) List. Iterator. add(E element) O(1) main benefit O(n-index) 23

How to Test Performance? long start = System. current. Time. Millis(); do. Somthing(); long

How to Test Performance? long start = System. current. Time. Millis(); do. Somthing(); long end = System. current. Time. Millis(); System. err. println(end - start); 24

set 25

set 25

Set A set is a an unordered list of disjoint elements {1, 2, 3,

Set A set is a an unordered list of disjoint elements {1, 2, 3, 1, 4, 2} = {4, 3, 2, 1} set. add(1) set. add(2) set. add(3) set. add(1) set. remove(1) Set {3, 2} 26

Set A set is a list with no duplicate Suppose we want to implement

Set A set is a list with no duplicate Suppose we want to implement such a class How? ! 27

Set Implementation class Set<E> extends Array. List<E>{ public boolean add(E e) { if(!contains(e)) return

Set Implementation class Set<E> extends Array. List<E>{ public boolean add(E e) { if(!contains(e)) return super. add(e); return false; }; public boolean add(int index, E e) {. . . } } 28

Set and equals() Method When set. add(value) is invoked It checks whethere is any

Set and equals() Method When set. add(value) is invoked It checks whethere is any element equal to value If any equal element found, add will return We should implement appropriate equals() method equals() is invoked implicitly 29

hash. Code() is one of Object methods like equals, to. String and finalize It

hash. Code() is one of Object methods like equals, to. String and finalize It creates a hash from the object Used in classes like Hash. Map and Hash. Set for faster retrieval 30

Hash function 31

Hash function 31

Hash. Set is an interface public interface Set<E> extends Collection<E> Hash. Set is one

Hash. Set is an interface public interface Set<E> extends Collection<E> Hash. Set is one of its (popular) implementations Set and Hash. Set are generic classes public class Hash. Set<E> implements Set<E> 32

Hash. Set Example Set<String> set= new Hash. Set<String>(); set. add("Ali"); set. add("Taghi"); set. add("Ali");

Hash. Set Example Set<String> set= new Hash. Set<String>(); set. add("Ali"); set. add("Taghi"); set. add("Ali"); for (String string : set) { System. out. println(string); } 33

Hash. Set Example Set<Student> set= new Hash. Set<Student>(); set. add(new Student("Ali")); set. add(new Student("Taghi"));

Hash. Set Example Set<Student> set= new Hash. Set<Student>(); set. add(new Student("Ali")); set. add(new Student("Taghi")); set. add(new Student("Ali")); set. remove(new Student("Taghi")); for (Student student : set) { System. out. println(student); } 34

Set or List? List provides access via an index Set does not List is

Set or List? List provides access via an index Set does not List is ordered Set checks for duplicates List is (usually) better in performance Set may be better in memory consumption Should we allow duplicates? If not, use sets Hash. Set is not implemented by a List 35

Hash and immutable objects Immutable object is better for work with hash Memory location

Hash and immutable objects Immutable object is better for work with hash Memory location is not good for hash seed Object content is better Mutable object can misguide hash function. 36

map 37

map 37

Map is not a collection Map is a table public interface Map<K, V> is

Map is not a collection Map is a table public interface Map<K, V> is something like a List<Pair<K, V>> First element of each pair is called the key Second element of each pair is called the value Duplicate for keys is not allowed Duplicate for values is possible 38

Map <K, V> map. put(87300876, “Ali Alavi”) 87300876 Ali Alavi map. put(87234431, “Taghi Taghavi”)

Map <K, V> map. put(87300876, “Ali Alavi”) 87300876 Ali Alavi map. put(87234431, “Taghi Taghavi”) 87300876 87234431 Ali Alavi Taghavi map. put(87300876, “Naghi Naghavi”) 87300876 87234431 39 Naghi Naghavi Taghavi

public interface Map<K, V> { int size(); boolean is. Empty(); boolean contains. Key(Object key);

public interface Map<K, V> { int size(); boolean is. Empty(); boolean contains. Key(Object key); boolean contains. Value(Object value); V get(Object key); V put(K key, V value); V remove(Object key); void put. All(Map<? extends K, ? extends V> m); void clear(); Set<K> key. Set(); Collection<V> values(); Set<Map. Entry<K, V>> entry. Set(); interface Entry<K, V> { K get. Key(); V get. Value(); V set. Value(V value); } } 40

Hash. Map is an interface public interface Map<K, V> { Hash. Map is one

Hash. Map is an interface public interface Map<K, V> { Hash. Map is one of its (popular) implementations public class Hash. Map<K, V> implements Map<K, V> 41

Hash. Map Example Map<Integer, String> map = new Hash. Map<Integer, String>(); map. put(87300876, "Ali

Hash. Map Example Map<Integer, String> map = new Hash. Map<Integer, String>(); map. put(87300876, "Ali Alavi"); map. put(87234431, "Taghi Taghavi"); map. put(87300876, "Naghi Naghavi"); String name = map. get(87300876); System. out. println(name); 42

Map<Student, Double> map = new Hash. Map<Student, Double>(); map. put(new Student("Ali Alavi"), new Double(18.

Map<Student, Double> map = new Hash. Map<Student, Double>(); map. put(new Student("Ali Alavi"), new Double(18. 76)); map. put(new Student("Taghi Taghavi"), new Double(15. 43)); map. put(new Student("Naghi Naghavi"), new Double(17. 26)); map. put(new Student("Naghi Naghavi"), new Double(15. 26)); map. remove(new Student("Naghi Naghavi")); Double average = map. get(new Student("Taghi Taghavi")); System. out. println("Avg of Taghi=" + average); for(Student student : map. key. Set()){ System. out. println(student. to. String()); } Double total. Sum = 0. 0; for(Double avg : map. values()){ total. Sum += avg; } System. out. println("Total Average = " + (total. Sum/map. size())); 43

Map application Map used to convert O(n) operation to O(1) Process and Memory tradeoff

Map application Map used to convert O(n) operation to O(1) Process and Memory tradeoff 44

iterator 45

iterator 45

Iterator is a mechanism for walking on elements of a collection Beforeach (before Java

Iterator is a mechanism for walking on elements of a collection Beforeach (before Java 5) it was the only mechanism iterator() is declared in Iterable interface In fact for-each is applicable on any Iterable object 46

Iterator public interface Iterable<T> { Iterator<T> iterator(); } public interface Collection<E> extends Iterable<E> {…}

Iterator public interface Iterable<T> { Iterator<T> iterator(); } public interface Collection<E> extends Iterable<E> {…} 47

Iterator Class public interface Iterator<E> { boolean has. Next(); E next(); void remove(); }

Iterator Class public interface Iterator<E> { boolean has. Next(); E next(); void remove(); } 48

Iterator Example Array. List<Integer> array. List = new Array. List<Integer>(); array. List. add(4); array.

Iterator Example Array. List<Integer> array. List = new Array. List<Integer>(); array. List. add(4); array. List. add(5); for (Integer next : array. List) { System. out. println(next); } Iterator<Integer> iterator = array. List. iterator(); while(iterator. has. Next()){ Integer next = iterator. next(); System. out. println(next); } 49

Concurrent Modification Suppose some processes are modifying the same collection Java containers have a

Concurrent Modification Suppose some processes are modifying the same collection Java containers have a mechanism to prevent it Suppose you’re in the middle of iterating through a container And then some other process steps in and changes an object in that container Insert, remove, … there are many scenarios for disaster. Maybe you’ve already passed that element in the container Maybe it’s ahead of you Maybe the size of the container shrinks after you call size( ) 50

Fail Fast Aspect If a collection is modified by one of its methods after

Fail Fast Aspect If a collection is modified by one of its methods after an iterator is created for that collection The iterator immediately becomes invalid Any operations performed with the iterator after this point throw Concurrent. Modification. Exceptions For this reason, iterators are said to be “fail fast” 51

Concurrent. Modification. Exception public class Fail. Fast { public static void main(String[] args) {

Concurrent. Modification. Exception public class Fail. Fast { public static void main(String[] args) { Collection<String> c = new Array. List<String>(); Iterator<String> it = c. iterator(); c. add("An object"); String s = it. next(); } } 52

Concurrent. Modification. Exception Array. List<Integer> list = new Array. List<Integer>(); list. add(1); list. add(2);

Concurrent. Modification. Exception Array. List<Integer> list = new Array. List<Integer>(); list. add(1); list. add(2); list. add(3); list. add(4); for (Integer integer : list) if(integer. equals(2)) list. remove(integer); 53

Use remove list Array. List<Integer> remove. List = new Array. List<Integer>(); for (Integer integer

Use remove list Array. List<Integer> remove. List = new Array. List<Integer>(); for (Integer integer : list){ if(integer. equals(2)){ remove. List. add(integer); }} list. remove. All(remove. List); 54

Java. uitils useful classes 55

Java. uitils useful classes 55

Java. util. Arrays A utility class with many useful static methods For arrays With

Java. util. Arrays A utility class with many useful static methods For arrays With methods for Copy Fill Sort Search … 56

Arrays Long[] array = new Long[100]; Arrays. fill(array, 5); Long[] copy = Arrays. copy.

Arrays Long[] array = new Long[100]; Arrays. fill(array, 5); Long[] copy = Arrays. copy. Of(array, 200); //An unmodifiable list: List<Integer> as. List = Arrays. as. List(1, 2 , 3, 4); List<Long> as. List 2 = Arrays. as. List(array); Arrays. sort(array); 57

Java. util. Collections A utility class for collections Copy Fill Sort Search … 58

Java. util. Collections A utility class for collections Copy Fill Sort Search … 58

Collections 59

Collections 59

Other Containers 60

Other Containers 60

Quiz Write the method remove. Alis(List<String> names) It takes a List<String> as parameter Removes

Quiz Write the method remove. Alis(List<String> names) It takes a List<String> as parameter Removes all the elements which start with “Ali” If(str. starts. With(“Ali”)){…} 61

Bad Implementation static void remove. Ali(List<String> list){ for (String string : list) if(string. starts.

Bad Implementation static void remove. Ali(List<String> list){ for (String string : list) if(string. starts. With("Ali")) list. remove(string); } Concurrent. Modification. Exception Which line? 62

Good Implementation public static void remove. Ali(Array. List<String> list){ Iterator<String> iterator = list. iterator();

Good Implementation public static void remove. Ali(Array. List<String> list){ Iterator<String> iterator = list. iterator(); while(iterator. has. Next()) { String string = iterator. next(); if(string. starts. With("Ali")) iterator. remove(); } 63

Good Implementation public static void remove. Ali(Array. List<String> list){ for (Iterator<String> iterator = list.

Good Implementation public static void remove. Ali(Array. List<String> list){ for (Iterator<String> iterator = list. iterator(); iterator. has. Next(); ) { String string = iterator. next(); if(string. starts. With("Ali")) iterator. remove(); } } List<String> list = new Array. List<String>(Arrays. as. List("Ali", "Ali. Reza", "Taghi")); remove. Ali(list); 64

Another Correct Implementation public static void remove. Ali(Array. List<String> list){ for (int i =

Another Correct Implementation public static void remove. Ali(Array. List<String> list){ for (int i = list. size()-1; i >= 0; i--) if(list. get(i). starts. With("Ali")) list. remove(i); } 65

end 66

end 66