Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones EE 422CGenerics 1.

Slides:



Advertisements
Similar presentations
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Advertisements

Written by: Dr. JJ Shepherd
Generic programming in Java
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
CS 307 Fundamentals of Computer Science ADTS and Generic Data Structures 1 Topic 12 ADTS, Data Structures, Java Collections and Generic Data Structures.
1 Topic 10 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.”
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,
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
CS10092 : Inheritance in Java (#2 of 4) Gavin Brown
Arrays And ArrayLists - S. Kelly-Bootle
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CS 307 Fundamentals of Computer ScienceInterfaces and Abstract Classes 1 Topic 7 Interfaces and Abstract Classes “I prefer Agassiz in the abstract, rather.
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.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
1 Abstract Classes “I prefer Agassiz in the abstract, rather than in the concrete.” CS Computer Science II.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
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.
Types in programming languages1 What are types, and why do we need them?
Type == Class  reference type -- store only the object’s address  simple (primitive) type -- for storing small data values Other options Wrapper classes.
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
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.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
CMSC 330: Organization of Programming Languages Java Generics.
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.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
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.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
1 Topic 5 Polymorphism "“Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.”
Sixth Lecture ArrayList Abstract Class and Interface
Polymorphism.
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:

Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones EE 422CGenerics 1

Covariance of arrays Employee [] array = new Lawyer[10]; Compiles, because a Lawyer IS-A Employee, and Java allows this. Since a Lawyer IS-A Employee, a Lawyer [] IS-A Employee []. You can pass in a Lawyer [] as a parameter to a method that asks for an Employee []. EE 422CGenerics 2

Covariance of return types class Marketer extends Employee { public Object doSomething () { return new Object(); } class Advertiser extends Marketer public Employee doSomething () { return new Employee(10); } Override does not give compile error. Covariant return types. EE 422CGenerics 3

EE 422CGenerics 4 Back to our Array Based List  Didn't want to have to write a new list class for every data type we want to store in lists  Used an array of Object s to store the elements of the list // from array based list private Object[] myCon;

EE 422CGenerics 5 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

EE 422CGenerics 6 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

EE 422CGenerics 7 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

EE 422CGenerics 8 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?

EE 422CGenerics 9 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? EE 422CGenerics 10

EE 422CGenerics 11 "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) ); }

EE 422CGenerics 12 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

EE 422CGenerics 13 Making our Array List Generic 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 ();

EE 422CGenerics 14 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

EE 422CGenerics 15 Using Generic Types  Back to Java's ArrayList ArrayList list1 = new ArrayList(); –still allowed, a "raw" ArrayList –works just like our Array –casting, lack of type safety

EE 422CGenerics 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

EE 422CGenerics 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

EE 422CGenerics 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