GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.

Slides:



Advertisements
Similar presentations
New features in JDK 1.5 Can these new and complex features simplify Java development?
Advertisements

Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Generic programming in Java
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
Bag implementation Add(T item) – Enlarge bag if necessary; allocate larger array Remove(T item) – Reduce bag if necessary; allocate smaller array Iterator.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 15 CS2110 – Spring 2015.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 13 CS2110 – Spring 2014.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
ArrayList, Multidimensional Arrays
Chapter 18 Java Collections Framework
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Generics CompSci 230 S Software Construction.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Types in programming languages1 What are types, and why do we need them?
Introduction to Generics
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
1 Interfaces in Java’s Collection Framework Rick Mercer.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
CMSC 330: Organization of Programming Languages Java Generics.
GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 15 CS2110 – Fall 2013.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Polymorphism (generics) CSE 331 University of Washington.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
List Interface and Linked List Mrs. Furman March 25, 2010.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Interfaces & Sub-types Weiss sec Scenario Instructor says: “Implement a class IntegerMath with two methods pow and fact with the following signatures:
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
Sixth Lecture ArrayList Abstract Class and Interface
Java Generics Lecture 14 CS2110 – Fall 2016
Java Generics Lecture 17 CS2110 – Spring 2017
Java Generics.
Java Generics Lecture 22 CS2110 – Fall 2018
Lecture 26: Advanced List Implementation
Generic programming in Java
Java Generics Lecture 22 CS2110 – Fall 2018
Generic Types and the Java Collections Framework
MINI-MAX using trees and the Java Collections Framework
Generics 2-May-19.
Presentation transcript:

GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy

Textbook and Homework Generics: Appendix B Generic types we discussed: Chapters 1-3, 15 Useful tutorial: docs.oracle.com/javase/tutorial/extra/generics/index.html 2

Early versions of Java lacked generics… 3 Java Collections interface Collection { /* Return true if the collection contains o */ boolean contains(Object o); /* Add o to the collection; return true if *the collection is changed. */ boolean add(Object o); /* Remove o fromthe collection; return true if * the collection is changed. */ boolean remove(Object o);... }

4 Java Collections Collection c =... c.add(“Hello”) c.add(“World”);... for (Object o : c) { String s = (String) o; System.out.println(s.length + “ : “ + s.length()); } The lack of generics was painful when using collections, because programmers had to insert manual casts into their code...

5 Using Java Collections String [] a =... a[0] = (“Hello”) a[1] = (“World”);... for (String s : a) { System.out.println(s); } This limitation was especially awkward because built- in arrays do not have the same problem! So, in the late 1990s Sun Microsystems initiated a design process to add generics to the language...

6 Arrays → Generics Object[] a =... String[] a =... Integer[] a =... Button[] a =... One can think of the array “brackets” as a kind of parameterized type: a type-level function that takes one type as input and yields another type as output We should be able to do the same thing with object types generated by classes!

7 Proposals for adding Generics to Java PolyJPizza/GJ LOOJ

With generics, the Collection interface becomes... 8 Generic Collections interface Collection { /* Return true if the collection contains x */ boolean contains(T x); /* Add x to the collection; return true if *the collection is changed. */ boolean add(T x); /* Remove x fromthe collection; return true if * the collection is changed. */ boolean remove(T x);... }

9 Using Java Collections Collection c =... c.add(“Hello”) c.add(“World”);... for (String s : c) { System.out.println(s.length + “ : “ + s.length()); } With generics, no casts are needed... Terminology: a type like Collection is called an instantiation of the parameterized type Collection.

10 Static Type checking Collection c =... c.add(“Hello”) /* Okay */ c.add(1979); /* Illegal: static error! */ The compiler can automatically detect uses of collections with incorrect types... Generally speaking, an instantiation like Collection behaves like the parameterized type Collection where all occurrences of T have been substituted with String.

Subtyping extends naturally to generic types. 11 Subtyping interface Collection {... } interface List extends Collection {... } class LinkedList implements List {... } class ArrayList implements List {... } /* The following statements are all legal. */ List l = new LinkedList (); ArrayList a = new ArrayList (); Collection c = a; l = a c = l;

String is a subtype of object so......is LinkedList a subtype of LinkedList ? 12 Subtyping LinkedList ls= new LinkedList (); LinkedList lo= new LinkedList (); lo= ls; //OK, if subtypes lo.add(2110); //OK: Integer subtype Object String s = ls.last(); //OK: elements of ls are strings But what would happen at run-time if we were able to actually execute this code?

Java’s type system allows the analogous rule for arrays :-/ 13 Array Subtyping String[] as = new String[10]; Object[] ao= new Object[10]; ao = as; //OK, if subtypes ao[0] = 2110; //OK: Integer subtype Object String s =as[0]; //OK: elements of s are strings What happens when this code is run? It throws an ArrayStoreException!

Suppose we want to write a helper method to print every value in a Collection. 14 Printing Collections void print(Collection c) { for (Object x : c) { System.out.println(x); }... Collection c =... c.add(42); print(c) /* Illegal: Collection is not a * subtype of Collection ! */

To get around this problem, Java’s designers added wildcards to the language 15 Wildcards void print(Collection c) { for (Object x : c) { System.out.println(x); }... Collection c =... c.add(42); print(c); /* Legal! */ One can think of Collection as a “Collection of unknown” values.

Note that we cannot add values to collections whose types are wildcards Wildcards void doIt(Collection c) { c.add(42); /* Illegal! */ }... Collection c =... doIt(c); /* Legal! */ More generally, can’t use any methods of Collection where the T occurrs in a “negative” position, like a parameter.

Sometimes it is useful to know some information about a wildcard. Can do this by adding bounds Bounded Wildcards void doIt(Collection c) { c.draw(this); }... Collection c =... doIt(c); /* Legal! */

Sometimes it is useful to know some information about a wildcard. Can do using bounds Bounded Wildcards void doIt(Collection > c) { for(Collection ci : c) { for(Object x : ci) { System.out.println(x); }... Collection ci =... Collection > c =... c.add(ci); doIt(c); /* Legal! */

Returning to the printing example, another option would be to use a method-level type parameter Generic Methods void print(Collection c) { for (T x : c) { System.out.println(x); }... Collection c =... c.add(42); print(c) /* More explicitly: this. print(c) */

Suppose we want to write a method to append each element of an array to a collection. 20 Appending an Array void m(T[] a, LinkedList l) { for (int i= 0; i < a.length, i++) { l.add(a[i]); }... List c =... Integer[] a =... m(a, l);

Suppose we want to print all elements that are “less than” a given element, generically. 21 Printing with Cutoff void printLessThan(Collection c, T x) { for (T y : c) { if ( /* y <= x ??? */ ) System.out.println(y); }

The Comparable interface declares a method for comparing one object to another. 22 Interface Comparable interface Comparable { /* Return a negative number, 0, or positive number * depending on whether this value is less than, * equal to, or greater than o */ int compareTo(T o); }

Suppose we want to print all elements that are “less than” a given element, generically. 23 Printing with Cutoff > void printLessThan(Collection c, T x) { for (T y : c) { if (y.compareTo(x) <= 0) System.out.println(y); }

Iterators: How “foreach” works The notation for(Something var: collection) { … } is syntactic sugar. It compiles into this “old code”: The two ways of doing this are identical but the foreach loop is nicer looking. You can create your own iterable collections 24 Iterator _i= collection.iterator(); while (_i.hasNext()) { E var= _i.Next();... Your code... }

java.util.Iterator (an interface) 25 public boolean hasNext();  Return true if the enumeration has more elements public E next();  Return the next element of the enumeration  Throw NoSuchElementException if no next element public void remove();  Remove most recently returned element by next() from the underlying collection  Throw IllegalStateException if next() not yet called or if remove() already called since last next()  Throw UnsupportedOperationException if remove() not supported

Efficiency Depends on Implementation 26  Object x= list.get(k);  O(1) time for ArrayList  O(k) time for LinkedList  list.remove(0);  O(n) time for ArrayList  O(1) time for LinkedList  if (set.contains(x))...  O(1) expected time for HashSet  O(log n) for TreeSet