63
Advanced Programming in Java Peyman Dodangeh Sharif University of Technology Spring 2014

Advanced Programming in Java

  • Upload
    truman

  • View
    31

  • Download
    0

Embed Size (px)

DESCRIPTION

Advanced Programming in Java. Peyman Dodangeh Sharif University of Technology Spring 2014. Agenda. Containers Collection Set Map LinkedList Iterator. Lists. Array. Suppose we have an array of students Student[] students = new Student[60]; What if we do not know the array size? - PowerPoint PPT Presentation

Citation preview

Advanced Programming in Java

Advanced Programming in JavaPeyman DodangehSharif University of TechnologySpring 20141AgendaContainersCollectionSetMapLinkedListIterator

Spring 2014Sharif University of Technology22ListsSpring 2014Sharif University of Technology3ArraySuppose we have an array of studentsStudent[] students = new Student[60];What if we do not know the array size?A default initial sizeWhat if we want to add more students to array?Double the size of arrayCopy old elementsWhat if we want to remove some students from array?Nullify the element & shift the othersWe need a dynamic arraySpring 2014Sharif University of Technology4Imagine if arrays was sth like:Student[] students = new Student[0];students.add(new Student("Ali Alavi"));students.add(new Student("Taghi Taghavi"));System.out.println(students[1]);students.remove(0);

But arrays are not so cute!

Spring 2014Sharif University of Technology5ArrayListJava introduces Collection classes for this purposeArrayList students = new ArrayList();students.add(new Student("Ali Alavi"));students.add(new Student("Taghi Taghavi"));students.remove(0);

Spring 2014Sharif University of Technology6Generic ArrayListArrayList is also a generic type

ArrayList students = new ArrayList();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);

ArrayList implements generic interface ListSpring 2014Sharif University of Technology7interface List{int size();boolean isEmpty();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 indexOf(Object o);int lastIndexOf(Object o);List subList(int fromIndex, int toIndex);}Spring 2014Sharif University of Technology8ArrayList list = new ArrayList();Scanner scanner = new Scanner(System.in);while(true){String input = scanner.next();if(input.equalsIgnoreCase("exit"))break;list.add(input);}if(list.isEmpty()){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);}}

Spring 2014Sharif University of Technology9For each is available for collectionsArrayList or Array? That is the question Do we need a dynamic array?AddRemovePerformance issueArrayList is implemented using an arraySpring 2014Sharif University of Technology10Array to ListGuess how?

String[] strings = {"ali", "taghi"};ArrayList list = new ArrayList();for (String string : strings) {list.add(string);}Spring 2014Sharif University of Technology11List to ArrayTwo methods:Object[] toArray(); T[] toArray(T[] a);

ArrayList list = new ArrayList();Object[] array = list.toArray();String[] array2 = list.toArray(new String[list.size()]);

Spring 2014Sharif University of Technology12Tell MeArrayList as;ArrayList ao;List lo;List ls;True/False?ArrayList is subclass of Listls = as;ArrayList is subclass of ArrayListao = as;ArrayList is subclass of Listlo=as;

Spring 2014Sharif University of Technology13ArrayList ImplementationIn the heart of an ArrayList, an array lives

public class ArrayList ... ,implements List,...{private Object[] elementData;private int size;public boolean add(E e) {ensureCapacity(size + 1); elementData[size++] = e;return true; }}Spring 2014Sharif University of Technology14Tell MeWhy toArray() returns Object[]?Spring 2014Sharif University of Technology15CollectionCollection is super-class of many containerspublic interface CollectionSome methods:int size();boolean isEmpty();boolean contains(Object o);boolean add(E e);boolean remove(Object o);void clear();Object[] toArray(); T[] toArray(T[] a);Spring 2014Sharif University of Technology16LinkedListLinkedList and ArrayList are both subclass of ListArrayList is implemented by an arrayLinkedList is implemented by a doubly linked listIt is used like an ArrayListBecause they are brothers! (subclass of List)Spring 2014Sharif University of Technology17Linked ListSpring 2014Sharif University of Technology18

Doubly Linked ListSpring 2014Sharif University of Technology19

LinkedList ExampleList list = new LinkedList();list.add("Ali");list.add("Taghi");System.out.println(list.get(0));list.remove("Taghi");for (String string : list) {System.out.println(string);}

Spring 2014Sharif University of Technology20ArrayList vs. LinkedListLinkedList stores two links for each elementif you want to do many insertions and removals in the middle of a lista LinkedList is better If not, an ArrayList is typically faster

Spring 2014Sharif University of Technology21Array, ArrayList and LinkedListSpring 2014Sharif University of Technology22

The "iteradd" test uses an iterator in the middle of the list to insert new elements.

The "insert" and "remove" tests both use location number 5 as the point of insertion or removal, rather than either end of the List.

the "add" test clears the List and then refills it to the specified list size 22How to Test Performance?long start = System.currentTimeMillis();

doSomthing();

long end = System.currentTimeMillis();

System.err.println(end - start);

Spring 2014Sharif University of Technology2323Quiz!Spring 2014Sharif University of Technology24

QuizImplement a LinkedList classSupport addremovegetSpring 2014Sharif University of Technology25SetSpring 2014Sharif University of Technology26SetA 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}

Spring 2014Sharif University of Technology27SetA set is a list with no duplicateSuppose we want to implement such a classHow?!Spring 2014Sharif University of Technology28Set Implementationclass Set extends ArrayList{public boolean add(E e) {if(!contains(e))return super.add(e);return false;};public boolean add(int index, E e) {...}}

Spring 2014Sharif University of Technology29Set and equals() MethodWhen set.add(value) is invokedIt checks whether there is any element equal to valueIf any equal element found, add will returnWe should implement appropriate equals() methodequals() is invoked implicitly

Spring 2014Sharif University of Technology30HashSetSet is an interfacepublic interface Set extends CollectionHashSet is one of its (popular) implementationsSet and HashSet are generic classespublic class HashSetimplements SetSpring 2014Sharif University of Technology31HashSet ExampleSet set= new HashSet();set.add("Ali");set.add("Taghi");set.add("Ali");for (String string : set) {System.out.println(string);}Spring 2014Sharif University of Technology32HashSet ExampleSet set= new HashSet();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);}Spring 2014Sharif University of Technology33Set or List?List provides access via an indexSet does notList is orderedSet checks for duplicatesList is (usually) better in performanceSet may be better in memory consumptionShould we allow duplicates?If not, use setsHashSet is not implemented by a ListSpring 2014Sharif University of Technology34MapSpring 2014Sharif University of Technology35MapMap is not a collectionMap is a tablepublic interface Map Map is something like a ListFirst element of each pair is called the keySecond element of each pair is called the valueDuplicate for keys is not allowedDuplicate for values is possible

Spring 2014Sharif University of Technology36Map map.put(87300876, Ali Alavi)

map.put(87234431, Taghi Taghavi)

map.put(87300876, Naghi Naghavi)

Spring 2014Sharif University of Technology3787300876Ali Alavi87300876Ali Alavi87234431Taghi Taghavi87300876Naghi Naghavi87234431Taghi Taghavipublic interface Map { int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); V get(Object key); V put(K key, V value); V remove(Object key); void putAll(Map