DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Similar documents
DM503 Programming B. Peter Schneider-Kamp.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach.

DM503 Programming B. Peter Schneider-Kamp.

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Java Collections Framework: Interfaces

Lecture 6: ArrayList Implementation

Generics Collection Framework

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

JAVA COLLECTION FRAMEWORK & SETS

CONTAİNERS COLLECTİONS

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Class 32: The Java Collections Framework

What is the Java Collections Framework?

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Outline. runtime of programs algorithm efficiency Big-O notation List interface Array lists

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

PIC 20A Collections and Data Structures

Algorithms. Produced by. Eamonn de Leastar

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

Generic classes & the Java Collections Framework. *Really* Reusable Code

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Java Review: Objects

Lecture 6 Collections

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Software 1 with Java. Recitation No. 6 (Collections)

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Lists. The List ADT. Reading: Textbook Sections

Working with arrays. ArrayLists. Abstraction. Arrays

CSE 143. Computer Programming II

ArrayLists. COMP1400 Week 8. Wednesday, 12 September 12

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

Model Solutions. COMP 103: Test April, 2013

CSC 1052 Algorithms & Data Structures II: Lists

CMSC 202H. Containers and Iterators

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Announcements/Follow-ups

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes.

Introduction to Collections

EXAMINATIONS 2016 TRIMESTER 2

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

EXAMINATIONS 2017 TRIMESTER 2

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

Use of the ArrayList class

Java Collection Framework

Dynamic Data Structures and Generics

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

CMSC 202. Containers

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

COMP 250. Lecture 29. interfaces. Nov. 18, 2016

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4

Linked List Nodes (reminder)

9/16/2010 CS Ananda Gunawardena

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

CS Ananda Gunawardena

Array Based Lists. Collections

The Java Collections Framework and Lists in Java Parts 1 & 2

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

List ADT. Announcements. The List interface. Implementing the List ADT

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Arrays and ArrayLists. David Greenstein Monta Vista High School

Review: List Implementations. CSE 143 Java. Links. A Different Strategy: Lists via Links. Linked Links. CSE143 Au List

Object-Oriented Design and Programming (Java)

CS 307 Final Spring 2008

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

CSC 321: Data Structures. Fall 2017

Vector (Java 2 Platform SE 5.0) Overview Package Class Use Tree Deprecated Index Help

Topic 10: The Java Collections Framework (and Iterators)

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

Collections and Iterators. Collections

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

CS 307 Midterm 2 Fall 2008

Outline. iterator review iterator implementation the Java foreach statement testing

COMP6700/2140 Abstract Data Types: Queue, Set, Map

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Programming II (CS300)

Interfaces, collections and comparisons

Chapter 5 Java Collection. j a v a c o s q q. c o m X i a n g Z h a n g

January 24, Abstract Data Types (ADTs) An ADT is an abstraction of a data structure.

Computational Expression

Transcription:

DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/

ABSTRACT DATATYPES 2

Abstract Datatype (ADT) abstract datatype = data + operations on the data Idea: encapsulate data + operations with uniform interface operations of a datatype at least one constructor modifiers / setters readers / getters computations ADTs typically specified by interfaces in Java 3

Abstract Datatype (ADT) abstract datatype = data + operations on the data when specifying an ADT, we describe the data and its logical organization which operations we want to be able to perform what the results of the operations should be we do NOT describe where and how the data is stored how the operations are performed ADTs are independent of the implementation (& language) one ADT can have many different implementations! 4

Examples for ADTs Numbers: (integer, rational or real) addition, subtraction, multiplication, division, Collections: (collections of elements) List: (ordered collections of elements) Stack (insert & remove elements at one end) Queue (insert at one end, remove at the other) Set: (unordered collection without duplicates) SortedSet (ordered collection without duplicates) Map: (mapping from keys to values) 5

Developing ADTs three steps (like in programming!) 1. specification of an ADT by mathematical means focus on WHAT we want 2. design (still independent of implementation & language) which data structures to use which algorithms to use focus on efficiency of representation and algorithms different data structures give different efficiency for operations 3. implementation (language dependent) select right programming language! implement design in that programming language 6

Specification of an ADT mathematically precise! data is represented by mathematical objects Example: real numbers operations are mathematical functions explicit specifications Example: indirect specifications Example: f (x) = x 2 R sqrt : x R 0 y R 0 x = y 2 y 0 7

specification: data: all n Ν Integer ADT operations: addition +, subtraction -, negation -, multiplication *, division /, modulo % Design 1: use primitive data type int use primitive operations Implementation 1: nothing to implement when using Java Design 2: use array of bytes to store bit provide all relevant operations Implementation 2: see class java.math.biginteger 8

Integer ADT specifying by mathematics often cumbersome alternatively use interfaces to specify operations alternative specification: data: all n Ν operations: public interface MyInteger { public MyInteger add(myinteger val); // addition public MyInteger sub(myinteger val); // subtraction public MyInteger neg(); // negation public MyInteger mul(myinteger val); // multplication public MyInteger div(myinteger val); // division 9

ABSTRACT DATATYPE FOR LISTS 10

List ADT: Specification data are all lists of integers, here represented as primitive int operations are defined by the following interface public interface ListOfInt { public int get(int i); // get i-th integer (0-based) public void set(int i, int elem); // set i-th element public int size(); // return length of list public void add(int elem); // add element at end public void add(int i, int elem); // insert element at pos. i public void remove(int i); // remove i-th element 11

Partially Full Arrays arrays are fixed-length lists are variable-length Idea: use an array of (fixed) length track number of elements in variable Example: add(23) add(42) add(-3) remove(0) add(1, 23) num 012323 data 23 42 42 23-3 -3 12

List ADT: Design & Implementation 1 Design 1: partially full arrays of int Implementation 1: public class PartialArrayListOfInt implements ListOfInt { private int limit; // maximal number of elements private int[] data; // elements of the list private int num = 0; // current number of elements public PartialArrayListOfInt(int limit) { this.limit = limit; this.data = new int[limit]; 13

List ADT: Implementation 1 Implementation 1 (continued): public class PartialArrayListOfInt implements ListOfInt { private int[] data; private int num = 0; public int get(int i) { if (i < 0 i >= num) { throw new IndexOutOfBoundsException(); return this.data[i]; 14

List ADT: Implementation 1 Implementation 1 (continued): public class PartialArrayListOfInt implements ListOfInt { private int[] data; private int num = 0; public void set(int i, int elem) { if (i < 0 i >= num) { throw new IndexOutOfBoundsException(); this.data[i] = elem; 15

List ADT: Implementation 1 Implementation 1 (continued): public class PartialArrayListOfInt implements ListOfInt { private int[] data; private int num = 0; public int size() { return this.num; public void add(int elem) { this.add(this.num, elem); // insert at end 16

List ADT: Implementation 1 Implementation 1 (continued): public class PartialArrayListOfInt implements ListOfInt { public void add(int i, int elem) { if (i < 0 i > num) { throw new Index Exception(); if (num >= limit) { throw new RuntimeException("full!"); for (int j = num-1; j >= i; j--) { this.data[j+1] = this.data[j]; // move elements right this.data[i] = elem; // insert new element num++; // one element more! 17

List ADT: Implementation 1 Implementation 1 (continued): public class PartialArrayListOfInt implements ListOfInt { public void remove(int i) { if (i < 0 i >= num) { throw new Index Exception(); for (int j = i; j+1 < num; j++) { this.data[j] = this.data[j+1]; // move elements left num--; // one element less! // DONE! 18

Dynamic Arrays arrays are fixed-length lists are variable-length Idea: use an array of (fixed) length & track number of elements extend array as needed by add method add(23) add(42) add(-3) add(17) add(31) Example: num 01 23 45 data 23 42-3 17 31 19

List ADT: Design & Implementation 2 Design 2: dynamic arrays of int Implementation 2: public class DynamicArrayListOfInt implements ListOfInt { private int limit; // current maximum number private int[] data; // elements of the list private int num = 0; // current number of elements public DynamicArrayListOfInt(int limit) { this.limit = limit; this.data = new int[limit]; 20

List ADT: Implementation 2 Implementation 2 (continued): public void add(int i, int elem) { if (i < 0 i > num) { throw new Index Exception(); if (num >= limit) { // array is full int[] newdata = new int[2*this.limit]; for (int j = 0; j < limit; j++) { newdata[j] = data[j]; this.data = newdata; this.limit *= 2; // rest of add method 21

List ADT: Design 2 Revisited Design 2 (revisited): symmetric dynamic arrays of int keep startindex and endindex of used indices start with startindex = endindex = limit / 2 i.e., limit / 2 free positions at the beginning i.e., limit / 2 free positions at the end extend array at the beginning when startindex < 0 needed extend array at the end when endindex > limit needed shrink array in remove, when (endindex startindex) < limit / 4 22

List ADT: Design 3 goal is to use list for arbitrary data types Design 3: dynamic arrays of objects How to use with Implementation 3: int, double etc.? public class DynamicArrayList implements List { private int limit; // current maximum number private Object[] data; // elements of the list private int num = 0; // current number of elements public DynamicArrayListOfInt(int limit) { this.limit = limit; this.data = new Object[limit]; 23

Boxing and Unboxing primitive types like int, double, are not objects! Java provides wrapper classes Integer, Double, Example: Integer myinteger = new Integer(13); int myint = myinteger.intvalue(); transparent due to automatic boxing and unboxing Example: Integer myinteger = 13; int myint = myinteger; useful when e.g. storing int values in a Object[] 24

List ADT: ArrayList Java provides pre-defined symmetric dynamic array list implementation in class java.util.arraylist Example: ArrayList mylist = new ArrayList(10); // initial limit 10 for (int i = 0; i < 100; i++) { mylist.add(i*i); // list of squares of 0 99 System.out.println(myList); for (int i = 99; i >= 0; i--) { int n = (Integer) mylist.get(i); // get returns Object mylist.set(i, n*n); // now to the power of 4! 25

Generic Types type casts for accessing elements are unsafe! solution is to use generic types instead of using an array of objects, use array of some type E Example: public class MyArrayList<E> implements List<E> { private E[] data; public E get(int i) { return this.data[i]; 26

List ADT: MyArrayList (generic) Unsafe type casts avoided when using generic types Example: MyArrayList<Integer> mylist = new MyArrayList<Integer>(); for (int i = 0; i < 100; i++) { mylist.add(i*i); // list of squares of 0 99 System.out.println(myList); for (int i = 99; i >= 0; i--) { int n = mylist.get(i); // get returns Integer mylist.set(i, n*n); // now to the power of 4! 27

List ADT: ArrayList (generic) Unsafe type casts avoided when using generic types Example: ArrayList<Integer> mylist = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) { mylist.add(i*i); // list of squares of 0 99 System.out.println(myList); for (int i = 99; i >= 0; i--) { int n = mylist.get(i); // get returns Integer mylist.set(i, n*n); // now to the power of 4! 28

COLLECTION CLASSES & GENERIC PROGRAMMING 29

Java Collections Framework Java comes with a wide library of collection classes Examples: ArrayList TreeSet HashMap idea is to provide well-implemented standard ADTs your own ADTs can build upon this foundation collection classes store arbitrary objects all collection classes implement Collection or Map thus, simple and standardized interface across different classes 30

Generic Programming the use of generic types is referred to as generic programming generic types can and should be used: by the user of collection classes Example: List<String> list = new ArrayList<String>(); when implementing ADTs Example: public class MyCollection<E> when implementing constructors and methods Example: public E getelement(int index) { when implementing static functions Example: public static <E> void add(listnode<e> n, E elem); 31

Generic Programming when a class has parameter type <E>, E is used like normal type instances of the class are defined by substituting concrete type Example: public class Mine<E> Mine<String> mine = more than one parameter is possible Example: public interface Map<K,V> when defining static function, prefix return type by parameter <E> inside function, E is used like normal type Example: public static <E> void add(listnode<e> n, E elem); 32

Generic Programming we can define that a parameter type extends some interface/class Example: public interface BinTree<E extends Comparable> { then all types E are usable, that implement Comparable using? we can define wildcard types Example: public boolean addall(collection<? extends E> c) { here, elements can be any type that extends E the same works with? super E 33

Collection ADT: Specification interface Collection<E> specifies standard operations boolean isempty(); // true, if there are no elements int size(); // returns number of elements boolean contains(object o); // is object element? boolean add(e e); // add an element; true if modified boolean remove(object o); // remove an element Iterator<E> iterator(); // iterate over all elements boolean addall(collection<? extends E> c); // add all clear, containsall, removeall, retainall, toarray, operations make sense both for lists, queues, stacks, sets, next: interface Iterator<E> 34

Iterator ADT: Specification iterate over elements of collections (= data) operations defined by interface Iterator<E>: public interface Iterator<E> { public boolean hasnext(); // is there another element? public E next(); // get next element public void remove(); // remove current element can be used to access all elements of the collection order is determined by specification or implementation 35

Iterator ADT: Example 1 Example (iterate over all elements of an ArrayList): ArrayList<String> list = new ArrayList<String>(); list.add("hej"); list.add("med"); list.add("dig"); Iterator<String> iter = list.iterator(); while (iter.hasnext()) { String str = iter.next(); System.out.println(str); no need to iterative over indices 0, 1,, list.size()-1 36

Extended for Loop also called for each loop iterative over each element of an array or a collection Example 1 (summing elements of an array): int[] numbers = new int[] {1, 2, 3, 5, 7, 11, 13; int sum = 0; for (int n : numbers) { sum += n; Example 2 (multiplying elements of a list): List<Integer> list = new ArrayList(Arrays.asList(numbers)); int prod = 1; for (int i : list) { prod *= i; 37

List ADT: Usage interface List<E> extends Collection<E> additional operation that make no sense for non-lists (e.g. get) can be sorted by static method in class Collections Example: int[] numbers = new int[] {1, 2, 3, 5, 7, 11, 13; List<Integer> list = new ArrayList(Arrays.asList(numbers)); Collections.sort(list); requires that elements implement Comparable full signature: public static <T extends Comparable<? super T>> void sort(list<t> list); 38

List ADT: Implementations ArrayList based on dynamic arrays very good first choice in >90% of applications LinkedList based on doubly-linked lists has prev member variable pointing to previous list node useful when adding and removing a lot in the middle do not use for Queue use ArrayDeque instead! Vector based on dynamic arrays old implementation, not synchronized use ArrayList! Stack based on Vector do not use for Stack use ArrayDeque instead! 39