Java Generics.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Written by: Dr. JJ Shepherd
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
Generic Programming David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Generic Programming Amit Shabtay. March 3rd, 2004 Object Oriented Design Course 2 The Problem Assume we have a nice Stack implementation. Our stack receives.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
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.
Effective Java: Generics Last Updated: Spring 2009.
ArrayList, Multidimensional Arrays
Abstract Data Types. What’s on the menu? What’s an abstract data type? How do you implement it? ADT List.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
CMSC 330: Organization of Programming Languages Java Generics.
Polymorphism (generics) CSE 331 University of Washington.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
List Interface and Linked List Mrs. Furman March 25, 2010.
CSE 1201 Object Oriented Programming ArrayList 1.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
EKT472: Object Oriented Programming
CMSC 202 ArrayList Aug 9, 2007.
Objects First with Java CITS1001 week 4
Generic Programming David Rabinowitz.
Compsci 201 Midterm 1 Review
(like an array on steroids)
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Software Development Java Collections
ADT’s, Collections/Generics and Iterators
More on Java Generics Multiple Generic Types Bounded Generic Types
Introducing Java Generics and Collections
Java Generics Lecture 14 CS2110 – Fall 2016
Generics and Subtyping
Generic Programming David Rabinowitz.
A tree set Our SearchTree class is essentially a set.
Error Handling Summary of the next few pages: Error Handling Cursors.
Topic 6 Generic Data Structures
עקרונות תכנות מונחה עצמים תרגול 21: Generics
Generics (Parametric Polymorphism)
ArrayLists.
Generics 27-Nov-18.
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
A tree set Our SearchTree class is essentially a set.
CMSC 202 ArrayList Aug 9, 2007.
Generic programming in Java
Dynamic Data Structures and Generics
CMSC 202 ArrayList Aug 9, 2007.
Collections Not in our text.
slides created by Ethan Apter
Interator and Iterable
slides created by Marty Stepp
Dynamic Data Structures and Generics
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Java Programming Language
slides created by Alyssa Harding
Creating and Modifying Text part 3
Review: libraries and packages
Generics 2-May-19.
List Interface ArrayList class implements the List Interface
Web Design & Development Lecture 6
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

Java Generics

Basic Concept Without Generics The cast on line (3) is needed because the signature of List.add() is So the new Integer object “forgets” its type when added to the list and needs to be “reminded” recall in line (3). Obviously the Integer object still sits in the list even though our program also has a reference to it. List myIntList = new LinkedList(); // 1 myIntList.add(new Integer(0)); // 2 Integer x = (Integer) myIntList.iterator().next(); // 3 public void add(Object o);

Line (1.1) is possible because How It Can Be Misused Line (1.1) is possible because myIntList doesn’t know what kind of object it is supposed to store Line (3.1) succeeds at compile time because at compile time the list doesn’t actually exist so the compiler takes on faith that this cast will be ok. Line (3.1) fails at run time because the object being retrieved is a String and not an Integer so this cast is illegal. myIntList.add(“123”); // 1.1 . . . Integer I = (Integer) myIntList.iterator().next(); // 3.1

Generic Alternative The alternative is to add to the myIntList declaration a “contract” that you will only put Integer objects into the list. This is done by adding a type parameter to the data type declaration and construction. Just like List is an Interface that LinkedList implements, List<Integer> is also an Interface that LinkedList<Integer> implements. Now myIntList “knows” it will only store Integer objects so the cast on line (6) becomes unnecessary. List<Integer> myIntList = new LinkedList<Integer>(); // 4 myIntList.add(new Integer(0)); // 5 Integer x = myIntList.iterator().next(); // 6

Generic Alternative (2) Now, the attempt to assign a String to the list on line (4.1) fails at compile time (and not later, at run time). You’ve signed a contract to only put Integer objects in there and you are clearly breaking the contract. In general, failure at compile time is better than failure at run time. This difference between compile vs run time error detection means we really have done more than move the clutter around. myIntList.add(“123”); // 4.1 fails at compile time

How does lastIndexOf() do this? ArrayList Example The two Integer objects I created are different objects but are the same when compared with Integer.equals(). So lastIndexOf() finds the first object by comparing the second to it using Integer.equals(). How does lastIndexOf() do this? ArrayList <Integer> al = new Arraylist<Integer>(100); // initial capacity 100 al.add(new Integer(“123”); // adds a new element at the beginning of the list // succeeds because Integer has the correct constructor al.add(10,new Integer(4)); // adds a new Integer object at location 10. int loc = al.lastIndexOf(new Integer(4)); // returns 10 to loc

List Iterators (1): ArrayList<E> implements List<E> which extends Iterable<E>. Things which implement Iterable<E> have an enhanced version of the standard for-loop. Iterators let you walk through the elements of a list without worrying about indexing – 0, 1, 2, … for (E next: ArrayList<E>) int lastIndexOf(E e) { int temp = -1, index = -1; for (E next : this) { index++; if (next.equals(e)) temp = index; } return temp;

This type of for loop hides exactly how Iterators work List Iterators (2): This type of for loop hides exactly how Iterators work Please note: no indexes anywhere in either of these two examples. int lastIndexOf(E e) { int temp = -1, index = -1; Iterator<E> ii = this.iterator(); // the iterator object is distinct // from the list it manipulates while(ii.hasNext()) { // hasNext() tells you if more elements exist in the list index++; E f = ii.next(); // next() gets a reference to the next element. if (f.equals(e)) temp = index; } return temp;

The Interfaces In Question: These two snippets show a small portion of the List<E> interface and almost the entire Iterator<E> interface. Remember, each time you see <E> you are looking at a formal parameter type declaration. When you see something like <Integer> you are looking at an actual parameter type declaration. Because the latter is still only a “declaration” it is still only an “actual parameter type” and not an “actual parameter”. public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext();

How Does This Differ From C++? In C++ each parameterized collection like List<Integer> will have its own source and object code. In Java “one size fits all”. There is only one .class file for all LinkedList<E> code.

Generics and Subtyping: List<String> ls = new ArrayList<String>(); // 7 List<Object> lo = ls; // 8 We can assign an ArrayList reference to a List variable. Can we assign an ArrayList<Integer> reference to a List<Object> variable? If we could, then line 10 would fail at run time. We are trying to avoid this. The java compiler will object to line 8. lo.add(new Object()); // 9 String s = ls.get(0); // 10: attempts to assign an Object to a String!