Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones.

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Improving structure with inheritance Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts.
Generic programming in Java
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 Further OO Concepts (Part I) Further OO Concepts I - Polymorphism Overview l Polymorphism is Wonderful. l Usefulness of Up casting? l Method call binding?
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
1 Topic 4 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“
CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 1 Topic 12 ADTS, Data Structures, Java Collections and Generic Data Structures.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Arrays And ArrayLists - S. Kelly-Bootle
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Java Generics.
CS 307 Fundamentals of Computer ScienceInterfaces and Abstract Classes 1 Topic 7 Interfaces and Abstract Classes “I prefer Agassiz in the abstract, rather.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
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.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
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
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.
CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Topic 4 Inheritance.
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.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
CSE 143 Lecture 20 Abstract classes. 2 Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public.
CMSC 330: Organization of Programming Languages Java Generics.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones EE 422CGenerics 1.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
Topic 7 Interfaces I once attended a Java user group meeting where James Gosling (one of Java's creators) was the featured speaker. During the memorable.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Question of the Day  Move one matchstick to produce a square.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
1 Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Java Generics.
Topic 6 Generic Data Structures
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Polymorphism.
Generic programming in Java
Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Polymorphism.
Presentation transcript:

Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones

CS314Generics 2 Back to our Array Based List  Started with a list of ints  Don't want to have to write a new list class for every data type we want to store in lists  Moved to an array of Object s to store the elements of the list // from array based list private Object[] myCon;

CS314Generics 3 Using Object  In Java, all classes inherit from exactly one other class except Object which is at the top of the class hierarchy  Object variables can refer to objects of their declared type and any descendants –polymorphism  Thus, if the internal storage container is of type Object it can hold anything –primitives handled by wrapping them in objects. int – Integer, char - Character

CS314Generics 4 Difficulties with Object  Creating generic containers using the Object data type and polymorphism is relatively straight forward  Using these generic containers leads to some difficulties –Casting –Type checking  Code examples on the following slides

Clicker Question 1  What is output by the following code? GenericList list = new GenericList(); // 1 String name = "Olivia"; list.add(name); // 2 System.out.print( list.get(0).charAt(2) );// 3 A. i B. No output due to syntax error at line // 1 C. No output due to syntax error at line // 2 D. No output due to syntax error at line // 3 E. No output due to runtime error. CS314Generics 5

CS314Generics 6 Code Example - Casting  Assume a list class ArrayList li = new ArrayList(); li.add("Hi"); System.out.println( li.get(0).charAt(0) ); // previous line has syntax error // return type of get is Object // Object does not have a charAt method // compiler relies on declared type System.out.println( ((String)li.get(0)).charAt(0) ); // must cast to a String

CS314Generics 7 Code Example – type checking //pre: all elements of li are Strings public void printFirstChar(ArrayList li) { String temp; for(int i = 0; i < li.size(); i++) { temp = (String)li.get(i); if( temp.length() > 0 ) System.out.println( temp.charAt(0) ); } // what happens if pre condition not met?

CS314Generics 8 Too Generic?  Does the compiler allow this? ArrayList list = new ArrayList(); list.add( "Olivia" ); list.add( new Integer(12) ); list.add( new Rectangle() ); list.add( new ArrayList() ); A.Yes B.No

Is this a bug or a feature? CS314Generics 9

CS314Generics 10 "Fixing" the Method //pre: all elements of li are Strings public void printFirstChar(ArrayList li) { String temp; for(int i = 0; i < li.size(); i++) { if( li.get(i) instanceof String ){ temp = (String)li.get(i); if( temp.length() > 0 ) System.out.println( temp.charAt(0) ); }

CS314Generics 11 Generic Types  Java has syntax for parameterized data types  Referred to as Generic Types in most of the literature  A traditional parameter has a data type and can store various values just like a variable public void foo(int x)  Generic Types are like parameters, but the data type for the parameter is data type –like a variable that stores a data type –this is an abstraction. Actually, all data type info is erased at compile time

CS314Generics 12 Making our Array List Generic  Data type variables declared in class header public class GenericList {  The is the declaration of a data type parameter for the class –any legal identifier: Foo, AnyType, Element, DataTypeThisListStores –Sun style guide recommends terse identifiers  The value E stores will be filled in whenever a programmer creates a new GenericList GenericList li = new GenericList ();

CS314Generics 13 Modifications to GenericList  instance variable private E[] myCon;  Parameters on –add, insert, remove, insertAll  Return type on –get  Changes to creation of internal storage container myCon = (E[])new Object[DEFAULT_SIZE];  Constructor header does not change

Modifications to GenericList  Careful with the equals method  Recall type information is actually erased  use of wildcard  rely on the elements equals methods CS314Generics 14

CS314Generics 15 Using Generic Types  Back to Java's ArrayList ArrayList list1 = new ArrayList(); –still allowed, a "raw" ArrayList –works just like our first pass at GenericList –casting, lack of type safety

CS314Generics 16 Using Generic Types ArrayList list2 = new ArrayList (); –for list2 E stores String list2.add( "Isabelle" ); System.out.println( list2.get(0).charAt(2) ); //ok list2.add( new Rectangle() ); // syntax error

CS314Generics 17 Parameters and Generic Types  Old version //pre: all elements of li are Strings public void printFirstChar(ArrayList li){  New version //pre: none public void printFirstChar(ArrayList li){  Elsewhere ArrayList list3 = new ArrayList (); printFirstChar( list3 ); // ok ArrayList list4 = new ArrayList (); printFirstChar( list4 ); // syntax error

CS314Generics 18 Generic Types and Subclasses ArrayList list5 = new ArrayList (); list5.add( new Rectangle() ); list5.add( new Square() ); list5.add( new Circle() ); // all okay  list5 can store Shape objects and any descendants of Shape