Advanced Programming Generics Collections

Similar documents
Programare avansată Tipuri generice Colecții de date

Java Generics -- an introduction. Based on

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Collections Questions

PIC 20A Collections and Data Structures

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Collections. James Brucker

Java Collections Framework

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

Fundamental language mechanisms

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

Java Programming Unit 8. Selected Java Collec5ons. Generics.

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Generics Collection Framework

Overview of Java s Support for Polymorphism

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types

Generics method and class definitions which involve type parameters.

Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs

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

COMP6700/2140 Generic Types

תוכנה 1 מבני נתונים גנריים

Generics and collections

CSE 331 Software Design & Implementation

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

Generics with Type Bounds

Collections (Java) Collections Framework

generic programming alberto ferrari university of parma

JAVA SYLLABUS FOR 6 WEEKS

USAL1J: Java Collections. S. Rosmorduc

DM550 Introduction to Programming part 2. Jan Baumbach.

Java Magistère BFA

Generics. IRS W-9 Form

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

COURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017

Pieter van den Hombergh Richard van den Ham. February 8, 2018

Java Collections Framework reloaded

Binghamton University. CS-140 Fall Interfaces

CITS2210 Object-Oriented Programming. Topic 9. Java: Generics

Adam Blank Lecture 5 Winter 2015 CSE 143. Computer Programming II

DM550 Introduction to Programming part 2. Jan Baumbach.

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

Building Java Programs

Parametric polymorphism and Generics

301AA - Advanced Programming [AP-2017]

Chapter 10 Collections

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

Java: exceptions and genericity

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

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Software Engineering. Prof. Agostino Poggi

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

CMSC 202. Containers

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

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

Generic programming in OO Languages

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

The collections interfaces

Generics. Chapter Contents

Grouping Objects (I)

תוכנה 1 מבני נתונים גנריים

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Collections & Maps. Lecture 12. Collections & Maps

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Since it is an interface, we need a concrete class during its declaration. There are many ways to initialize a Queue object, most common being-

Lecture 6 Collections

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

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS **

301AA - Advanced Programming [AP-2017]

Tony Valderrama, SIPB IAP 2010

Building Java Programs

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

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

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

Model Solutions. COMP 103: Mid-term Test. 21st of August, 2014

CS 146 Spring 2017 Homework 4 Sections 5 and 6. The homework assignment is available at:

CMSC 341. Nilanjan Banerjee

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

Distributed Systems Recitation 1. Tamim Jabban

CMSC 202H. Containers and Iterators

Abstract classes are used to define a class that will be used only to build new classes. No objects will ever be instantiated from an abstract class.

Polymorphism (generics)

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

CSE 331 Software Design & Implementation

CS Programming Language Java. Fall 2004 Sept. 29

Interfaces. An interface defines a set of methods. An interface declaration contains signatures, but no implementations.

EECS2030 Week 7 worksheet Tue Feb 28, 2017

COMP6700/2140 Generic Methods

5/23/2015. Core Java Syllabus. VikRam ShaRma

CS108, Stanford Handout #8. Java Generics

Core Java Contents. Duration: 25 Hours (1 Month)

Notes on access restrictions

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

University of Maryland College Park Dept of Computer Science

Interfaces and Collections

Computer Science II (Spring )

Transcription:

Advanced Programming Generics Collections

The Context Create a data structure that stores elements: a stack, a linked list, a vector a graph, a tree, etc. What data type to use for representing the elements of the structure? Homogenous structure class Stack { private int[] items; public void push (int item) {... public int peek() { Stack stack = new Stack(); stack.push(100); stack.push(200); stack.push("hello World!"); Heterogeneous structure class Stack { private Object[] items; public void push (Object item) {... public Object peek() { Stack stack = new Stack(); stack.push(100); stack.push(new Rectangle()); stack.push("hello World!"); String s = (String) stack.peek;

Generics Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. public Stack<String> { Stronger type checks at compile time. stack.push(new Rectangle()); Elimination of casts. String s = (String) stack.peek(); Enabling generic algorithms.

Defining a Generic Type class ClassName<T1, T2,..., Tn> { or interface IName<T1, T2,..., Tn> { /** * A generic version of the Stack class * @param <E> the type of the elements */ public class Stack<E> { // E is a generic data type private E[] items; E is the type parameter public void push(e item) {... public E peek() {..

Type Parameter Naming Conventions E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th types public class Node<T> { public interface Pair<K, V> { public class PairImpl<K, V> implements Pair<K, V> {...

Instantiating a Generic Type Generic Invocation Stack<String> stack = new Stack<String>(); Pair<Integer,String> pair = new PairImpl<Integer,String>(0, "ab"); Stack<Node<Integer>> nodes = new Stack<Node<Integer>>(); The Diamond <> Stack<String> stack = new Stack<>(); String is the type argument Pair<Integer,String> pair = new PairImpl<>(0, "ab"); Stack<Node<Integer>> nodes = new Stack<>(); The compiler can determine, or infer, the type arguments from the context.

Generic Methods Generic methods are methods that introduce their own type parameters. public class Util { public static <T> int countnullvalues(t[] anarray) { int count = 0; for (T e : anarray) if (e == null) { ++count; return count; Util.countNullValues(new String[]{"a", null, "b"); Util.countNullValues(new Integer[]{1, 2, null, 3, null);

Bounded Type Parameters class D <T extends A & B & C> { /*... */ public class Node<T extends Number> { private T t; public void set(t t) { this.t = t; public T get() { return t; // Generic Method public <U extends Integer> void inspect(u u){ System.out.println("T: " + t.getclass().getname()); System.out.println("U: " + u.getclass().getname()); public static void main(string[] args) { Node<Double> node = new Node<>(); node.set(12.34); //OK node.inspect(1234); //OK node.inspect(12.34); //compile error! node.inspect("some text"); //compile error!

Generics, Inheritance, Subtypes "is a" Integer extends Object Integer extends Number Stack<Integer> extends Stack<Object> Stack<Integer> extends Stack<Number> Given two concrete types A and B (for example, Number and Integer), MyClass<A> has no relationship to MyClass<B>, regardless of whether or not A and B are related. The common parent of MyClass<A> and MyClass<B> is Object. This is a common misunderstanding when it comes to programming with generics, but it is an important concept to learn

Wildcards Upper bounded public double sumoflist(list<? extends Number> list) { //it works on List<Integer>, List<Double>, List<Number>, etc. double s = 0.0; for (Number n : list) s += n.doublevalue(); return s; Unbounded public void printlist(list<?> list) { for (Object elem: list) System.out.print(elem + " "); Lower bounded public void addnumbers(list<? super Integer> list) { //it works on List<Integer>, List<Number>, and List<Object> //anything that can hold Integer values. for (int i = 1; i <= 10; i++) { list.add(i);

Java Collections Framework

Java Collections Framework A collection is an object that groups multiple elements into a single unit. Vectors, Lists, Stacks, Sets, Dictionaries, Trees, Tables, etc. Promotes software reuse Reduces programming effort Increases program speed and quality Benefits from polymorphic algorithms Uses generics

Collections Framework Interface List Abstract class AbstractList Concrete implementation ArrayList LinkedList Vector

The Core Collection Interfaces

Implementations Interfața Hash Array Tree Linked Hash+Linked Set HashSet TreeSet LinkedHashSet List Queue ArrayList Vector LinkedList Deque ArrayDeque LinkedDeque Map HashMap Hashtable TreeMap LinkedHashMap Set set = new HashSet(); --raw generic type (Object) ArrayList<Integer> list = new ArrayList<>(); List<Integer> list = new ArrayList<>(); List<Integer> list = new LinkedList<>(); List<Integer> list = new Vector<>(); Map<Integer, String> map = new HashMap<>();

Collections Hierarchy

Iterating Over a Collection Indexed Collections for (i=0; i < list.size(); i++ ) { System.out.println( list.get(i) ); Iterator and Enumeration for (Iterator it = set.iterator(); it.hasnext(); ) { System.out.println(it.next()); it.remove(); for-each List<Student> students = new ArrayList<Student>();... for (Student student : students) { student.setgrade(10);

Aggregate Operations Stream - sequence of elements supporting sequential and parallel aggregate operations. Pipeline - a sequence of aggregate operations. persons.stream().filter(p -> p.getage() >= 18).filter(p -> p.getname().endswith("escu")).foreach(s -> System.out.println(s.getName())); Reduction and Terminal ops. double averageage = persons.stream().filter(p -> p.getage() >= 18).mapToInt(Person::getAge).average().getAsDouble(); Source array, collection,... Intermediate operations filter, distinct, sorted,... Reduction operations map, maptoint,... Terminal operations average, min, max,...

Polymorphic Algorithms java.util.collections sort shuffle binarysearch reverse fill copy min max swap enumeration unmodifiablecollectiontype List<String> immutablelist = Collections.unmodifiableList(list); immutablelist.add("oops...?!"); What DesignPattern? synchronizedcollectiontype

ArrayList or LinkedList? import java. util.*; public class Test { final static int N = 100000; public static void testadd ( List lst) { long t1 = System. currenttimemillis (); for (int i=0; i < N; i++) lst.add (new Integer (i)); long t2 = System. currenttimemillis (); System. out. println ("Add: " + (t2 - t1)); public static void testget ( List lst) { long t1 = System. currenttimemillis (); for (int i=0; i < N; i++) lst.get(i); long t2 = System. currenttimemillisa (); System. out. println ("Get: " + (t2 - t1)); public static void testremove ( List lst ) { long t1 = System. currenttimemillis (); for (int i=0; i < N; i++) lst.remove(0); long t2 = System. currenttimemillis (); System. out. println (" Remove : " + (t2 - t1)); public static void main ( String args []) { List lst1 = new ArrayList (); testadd ( lst1 ); testget ( lst1 ); testremove ( lst1 ); List lst2 = new LinkedList (); testadd ( lst2 ); testget ( lst2 ); testremove ( lst2 ); ArayList add 0.12 0.14 LinkedList get 0.01 87.45 remove 12.05 0.01 Conclusion: Choosing a certain implementation depends on the nature of the problem being solved.