Generics and Type Safety. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
|
|
- Julia Norman
- 6 years ago
- Views:
Transcription
1 Generics and Type Safety CS 180 Sunil Prabhakar Department of Computer Science Purdue University
2 Dynamic Data Collections Already seen several examples of dynamic data Linked list, Stack, Queue, Trees Java provides a number of such classes part of the Java Foundation Classes (JFC) e.g., Vector, HashMap, ArrayList An important issue with each of these is creating homogeneous collections e.g., a Stack of Students objects only how can we achieve this? Why? Type safety. 2
3 The Node Class for Strings class Node { private Node next; private String content; public Node() { next = null; content = null; public String getcontent(){ return content; public void setcontent(string s){ content = s; public Node getnext(){ return next; public void setnext(node nextnode){ next = nextnode;... String s1 = Hi ; Student student = new Student( Jane ); Node stringnode, studentnode; stringnode = new Node(); studentnode = new Node(); stringnode.setcontent(s1); studentnode.setcontent(student); s1 = stringnode.getcontent(); student = studentnode.getcontent();... Will not compile! 3
4 The Node Class for Students class Node { private Node next; private Student content; public Node( ) { next = null; content = null; public Student getcontent(){ return content; public void setcontent( Student s){ content = s; public Node getnext(){ return next; public void setnext(node nextnode){ next = nextnode;... String s1 = Hi ; Student student = new Student( Jane ); Node stringnode, studentnode; stringnode = new Node(); studentnode = new Node(); stringnode.setcontent(s1); studentnode.setcontent(student); s1 = stringnode.getcontent(); student = studentnode.getcontent();... Will not compile! 4
5 Problem Need a (slightly) different class for each homogeneous collection! What about the existing JFC classes? If we want a single class, then we are forced to have Object as the content! Now we are unable to enforce a homogeneous collection we can add objects of any class to these collections! 5
6 The General Node Class class Node { private Node next; private Object content; public Node( ) { next = null; content = null; public Object getcontent(){ return content; public void setcontent( Object s){ content = s; public Node getnext(){ return next; public void setnext(node nextnode){ next = nextnode;... String s1 = Hi ; Student student = new Student( Jane ); Node stringnode, studentnode; stringnode = new Node(); studentnode = new Node(); stringnode.setcontent(s1); studentnode.setcontent(student); s1 = (String) stringnode.getcontent(); student = (Student) stringnode.getcontent();... Exception Need to cast! 6
7 Generics How can we have a single class, yet enforce homogeneity? Solution: Generics (introduced in Java 1.5) Generics help achieve type safety enforce homogeneous collections improves compile-time checking and enforcement of types improves reliability of programs All JCF classes were retro-fitted to support generics. 7
8 The Generic Node class A generic class takes one (or more) type parameters The type parameter behaves like an argument that is a type (class) 8
9 The Generic Node Class class Node <T> { private Node next; private T content; public Node( ) { next = null; content = null; public T getcontent(){ return content; public void setcontent( T s){ content = s; public Node getnext(){ return next; public void setnext(node nextnode){ next = nextnode;... String s1 = Hi ; Student student = new Student( Jane ); Node <String> stringnode; Node <Student> studentnode; stringnode = new Node <String>(); studentnode = new Node <Student>(); stringnode.setcontent(s1); studentnode.setcontent(string); studentnode.setcontent(student); s1 = stringnode.getcontent(); s1 = studentnode.getcontent();... No casting Will not compile! 9
10 Generic classes and objects Depending upon the type specified for the type parameter when creating an object of the Node class, the compiler will perform the appropriate type checking. The content of stringnode can only be a String object (or descendants) The content of studentnode can only be an object of class Student (or descendants) This is exactly what we wanted We define only a single class, and We are able to limit the data types for different instances. 10
11 Generic classes It is important to realize that there is only one class called Node. stringnode and studentnode are both of class Node The class is called Node, the constructor is Node(). There are no Node<T>, or Node<String>, classes. However, even though they are from the same class, we cannot use them interchangeably: stringnode = studentnode; 11
12 Generic classes Node <String> stringnode = new Node <String> (); Node <Student> studentnode = new Node <Student> (); if (stringnode instanceof Node) System.out.println ("stringnode is a Bag object"); if (stringnode instanceof Node <T>) System.out.println ("stringnode is a Node<T> object"); if (stringnode instanceof Node <String>) System.out.println ("stringnode is a Node<String> object"); if (stringnode instanceof Node <Student>) System.out.println ("stringnode is a Node<Student> object"); Will not compile! 12
13 Primitive data A type parameter can only take a class data type. If we want to store primitive data in our Bag, then we have to convert it to its corresponding wrapper class. With Java 5 this is trivial due to autoboxing and auto unboxing. Node<Integer> intnode = new Node<Integer>(); int i = 5, j; intnode.store(new Integer(i)); intnode.store(i); j = intnode.retrieve(); j = intnode.retrieve().intvalue(); 13
14 Multiple Type Parameters We can have multiple type parameters in a generic class. class MapNode<T1, T2>{ private T1 key; private T2 content; private MapNode next; public MapNode(T1 k, T2 item, MapNode n){ storekey(k); storecontent(item); next = n; public T1 retrievekey(){ return key; public T2 retrievecontent(){ return content; public void store(t1 k, T2 item){ key = k; content = item; 14
15 Example MapNode<String, Student> maplist = null; String id = new String( ); Student st = new Student( Jane ); maplist = new MapNode<String, Student> (id, st, maplist); String s1 = maplist.retrievekey(); Student st1 = maplist.retrievecontent(); s1 = maplist.retrievecontent(); st1 = maplist.retrievekey(); Will not compile! 15
16 Example DualBag<Book, Book> pair = new DualBag<Book, Book> (); Book b1 = new Book(); Book b2 = new Book(); parr.storefirst(b1); pair.storesecond(b2); Both parameters can be of the same type. If we want to enforce this then we use only one parameter. class DualBag<T>{ private T content1; private T content2; public DualBag(){ storefirst(null); storesecond(null); public DualBag(T item1, T item2){ storefirst(item1); storesecond(item2); public T retrievefirst(){ return content1; public T retrievesecond(){ return content2; public void storefirst(t item){ content1 = item; public void storesecond(t item){ content2 = item; 16
17 Type Safety class BagA{ private Object content; public BagA(){ store(null) ; public Object retrieve(){ return content; public void store(object item) { content = item; class BagB<T>{ private T content; public BagB(){ store(null) ; public T retrieve(){ return content; public void store(t item){ content = item; These two are not the same. Only the generic class offers (compile time) type safety. The other may lead to runtime errors due to type mismatches. 17
18 Type Safety Which is better Have the compiler enforce type safety or Allow unsafe expressions and then have a runtime error? It is far better to catch such errors (which are likely to be logical errors) at compile time. Thus type safety is desirable. In addition to better reliability, note that with type safety there is no need for type casting or runtime type checking. This can improve the runtime of programs too. 18
19 Quiz class Node<T>{... Node <T> numnode = new Node <Number> (); Node <Integer> intnode = new Node <Integer> (); numnode = intnode; What is the class of variable numnode? A. Node<Number> B. Node<Integer> C. Node<T> D. Node 19
20 Bounded Types The current generic version of Node allows us to create instances to store any type of objects as content. What if we want to limit the types of objects that can be stored in our Node? We can do this by bounding the type parameter. Consider a Node class that only allows us to store numeric objects. 20
21 Bounded Type class NumBag<T extends Number>{ private T content; public NumBag(){ store(null) ; public NumBag(T item){ store(item) ; public T retrieve(){ return content; public void store(t item){ content = item; NumBag <Double> doublebag = new NumBag <Double> (); NumBag <Laptop> laptopbag = new NumBag <Laptop> (); NumBag <Number> numbag; doublebag.store(new Double(3.0)); numbag.store(new Number(12)); numbag.store(new Integer(12)); numbag = new NumBag<Double>(); Laptop Number No super-sub doesn t is an extend abstract relationship! Number class! Will not compile! 21
22 Wildcard types Suppose we would like to be able to check for equality of the number values stored in different instances of the NumBag class: NumBag<Double> bag1= new NumBag<Double>(new Double(3.0)); NumBag<Integer> bag2 = new NumBag<Integer>(new Integer(3)); if(bag1.issamevalue(bag2)) System.out.println( The values are the same. ); How should the issamevalue method be written? Note that it may be called on an object such as bag1 that stores doubles and receive an object such as bag2 that stores integers as a parameter. 22
23 Wildcard types class NumBag<T extends Number>{ private T content;... public boolean issamevalue(numbag<t> item){ return this.retrieve().doublevalue() == item.retrieve().doublevalue(); NumBag<Double> bag1= new NumBag<Double>(new Double(3.0)); NumBag< Integer> bag2 = new NumBag< Integer>(new Integer(3)); if(bag1.issamevalue(bag2)) System.out.println( The values are the same. ); Will not compile! 23
24 Wildcard types class NumBag<T extends Number>{ private T content;... public boolean issamevalue(numbag<?> item){ return this.retrieve().doublevalue() == item.retrieve().doublevalue(); NumBag<Double> bag1= new NumBag<Double>(new Double(3.0)); NumBag< Integer> bag2 = new NumBag< Integer>(new Integer(3)); if(bag1.issamevalue(bag2)) System.out.println( The values are the same. ); Okay as long as bag2 s content supports the doublevalue() method 24
25 Limitations of generics We are not allowed to Create an instance of the type parameter class within the generic class, or Use type parameters with static data members or static methods. The reason is that the actual type corresponding to the type parameter is known only when an object is instantiated. 25
26 Example class NumBag<T extends Number>{ private T content; private static T classcontent; public NumBag(){ content = new T(); store(content) ; public static T return classcontent; getclasscontent(){ Will not compile! 26
27 Java Collections Framework The JCF provides a large set of very commonly used classes such as ArrayList, Vector, Queue, In earlier releases of Java the JCF classes were unable to enforce types strongly. All JCF classes have been retrofitted in Java 5 to work correctly with generics. These classes are defined in java.util 27
28 (Old) JCF Example import java.util.*; List booklist = new ArrayList(); booklist.add(new Book( Wilder ); booklist.add(new Book( Nabokov ); booklist.add(new Book( William ); booklist.add( Shakespeare ); Iterator itr = booklist.iterator(); while(itr.hasnext()){ Book book = (Book) itr.next(); System.out.println(book.getAuthor()); Note the need for typecasting. Can add any type of object to this ArrayList. 28
29 Generics JCF Example import java.util.*; ArrayList<Book> booklist = new ArrayList<Book>(); booklist.add(new Book( Wilder ); booklist.add(new Book( Nabokov ); booklist.add(new Book( William ); booklist.add( Shakespeare ); Iterator<Book> itr = booklist.iterator(); while(itr.hasnext()){ Book book = itr.next(); System.out.println(book.getAuthor()); Iterator needs type too. Compile error. No need for typecasting. 29
30 New for statement Java 5 has also introduced a new variant of the for loop statement: for-each loop Eliminates the need for iterator objects for iterating through a collection. for(book book : booklist) { System.out.println(book.getAuthor()); General format: for (<type> <var> : <collection>) <stmt> Collection must be a JCF class and type must match the type of the collection. 30
31 for-each Example with ArrayList ArrayList<String> mylist = new ArrayList<String>(); mylist.add( Qian ); mylist.add( Achebe ); mylist.add( Lisa ); for(string str : mylist) { System.out.println(str); 31
32 for-each Example with arrays int number[] = {1, 3, 4, 5, 6 9; int sum = 0; for(int element : number) { sum += element; int sum = 0; for (int i = 0; i< number.length; i++) { sum += number[i]; NOTE: not allowed to change the value of loop variable of a for-each loop. 32
33 Non-generic ArrayList example ArrayList mylist = new ArrayList(); mylist.add( Qian ); mylist.add( Achebe ); mylist.add( Lisa ); for(object b : mylist) { System.out.println( Item is + (String)b ); 33
34 Raw Types & Backward Compatibility All the JCF class have been redefined to be generic classes. What about earlier programs not written for Java 5 using older JCF classes? In order to ensure backward compatibility, Java 5 allows a generic class to be created without specifying a type parameter! Essentially, the compiler assumes that the type is Object -- thus any class can be stored. If we don t specify the type, we get a raw type. Raw types do not have the benefit of type safety and should be avoided. 34
35 Arrays and generics Arrays should not be used with generics unless you wish to use raw types. Instead use the ArrayList or LinkedList class to create a generic array. In general, do not use raw types with generics. Their use is only for ensuring backward compatibility in legacy code written before Java 5. 35
36 Raw Types Bag bag = new Bag(); bag.store(new Integer(5)); bag.store( test ); bag.store(new Book( Ludlum )); Bag rawbag = new Bag(); Bag<String> strbag = new Bag<String>; Bag<Integer> intbag = new Bag<Integer>; intbag.store(new Integer(5)); rawbag = intbag; strbag = rawbag; String str = strbag.retrieve(); Dangerous, but allowed! 36
37 Limitations of Generics Cannot create a generic class for Exceptions Anonymous inner classes classes defined within another class, but with no name. E.g. as Action Handlers for GUIs Enum types Casting to a generic type generates a warning ( unchecked cast ) cast is to the raw type (with no type parameter) 37
38 No Inheritance for Generics List<Object> is not a super-type of List<Number> However, List<Number> is a super-type of ArrayList<Number>!!!! This only works if the type parameter is the same. Note that arrays behave differently: Object[] is a super-type to Number[] 38
39 Lots of subtleties with Generics See GenericsFAQ/JavaGenericsFAQ.html for an excellent treatment of generics in Java. 39
40 Generics, Inheritance & Interfaces It is possible to define a generic subclass of a non-generic class. It is also possible to define a subclass of a generic class IMPORTANT: in this case the subclass must also be generic, or fix the type parameter It is possible for a generic class to implement a non-generic interface. It is also possible for a class to implement a generic interface IMPORTANT: in this case the class must also be generic,or fix the type parameter 40
Announcements. Final exam. Course evaluations. No classes next week. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA. Wednesday November 28th
Announcements Final exam Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Course evaluations Wednesday November 28th No classes next week no lectures, labs, or recitations Happy Thanksgiving! 1 Generics
More informationObjects and Iterators
Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a
More informationCS108, Stanford Handout #8. Java Generics
CS108, Stanford Handout #8 Fall, 2007-08 Nick Parlante Java Generics Java generics (added in version 5) are a mixed bag. Some uses of generics are simple to understand and make the code cleaner. They are
More informationABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011
1 ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES Lecture 4 CS 2110 Summer 2011 Lists are Iterable 4 for public static void printlist(list strings) { for (int idx = 0; idx < strings.size();
More informationAnnouncements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation Lecture 15 Generics 2 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now
More informationCSE 331 Software Design and Implementation. Lecture 15 Generics 2
CSE 331 Software Design and Implementation Lecture 15 Generics 2 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now
More informationJava 1.5 in a Nutshell
Java 1.5 in a Nutshell Including Generics, Enumerated Types, Autoboxing/Unboxing, and an Enhanced for Loop http://java.sun.com/j2se/1.5.0/docs/guide/language/ CS 2334 University of Oklahoma Brian F. Veale
More informationCSIS 10B Lab 2 Bags and Stacks
CSIS 10B Lab 2 Bags and Stacks Part A Bags and Inheritance In this part of the lab we will be exploring the use of the Bag ADT to manage quantities of data of a certain generic type (listed as T in the
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More information1.1. Annotations History Lesson - C/C++
1. Additions Thanks to Dr. James Heliotis. He started it all :) See also here: and see also here: and here: You need to use the tools from the Java release candidate 1 % bash % export PATH=/usr/local/j2sdk1.5.0-rc1/bin:$PATH
More informationJava Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html
Java Generics -- an introduction Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Generics vs. Templates Templates in C++ are compiled into unique code based on the types passed
More informationJava Magistère BFA
Java 101 - Magistère BFA Lesson 4: Generic Type and Collections Stéphane Airiau Université Paris-Dauphine Lesson 4: Generic Type and Collections (Stéphane Airiau) Java 1 Linked List 1 public class Node
More informationJava 5 New Language Features
Java 5 New Language Features Ing. Jeroen Boydens, BLIN prof dr. ir. Eric Steegmans http://users.khbo.be/peuteman/java5/ Enterprise Programming Last session. Jeroen Boydens 1. JDK v1.4: assert 2. Generics
More informationIntroducing Generics
Generics Introducing Generics Generics allow reference types (classes, interfaces, and array types) and methods to be parameterized with type information. An abstract data type (ADT) defines both the types
More informationGeneric types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:
Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide
More informationClosed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha
Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide
More information09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013
1 TYPE CHECKING AND CASTING Lecture 5 CS2110 Spring 2013 1 Type Checking 2 Java compiler checks to see if your code is legal Today: Explore how this works What is Java doing? Why What will Java do if it
More informationJava: exceptions and genericity
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exceptions Exceptions
More informationLesson 26: ArrayList (W08D1)
Lesson 26: ArrayList (W08D1) Balboa High School Michael Ferraro October 5, 2015 1 / 25 Do Now Prepare PS #4a (paper form) for pick-up! Consider the code below for powiter(), an iterative algorithm that
More informationJava Intro 3. Java Intro 3. Class Libraries and the Java API. Outline
Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries
More informationCS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.
CS61B Lecture #24 Today: Java support for generic programming Readings for today: A Java Reference, Chapter 10. Readings for Monday: Data Structures, 6.4. Last modified: Fri Oct 19 19:33:03 2012 CS61B:
More informationAnnouncements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA
Announcements Final exam Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Course evaluations Wednesday November 28th Need volunteer to collect evaluations and deliver them to LWSN. 1 Chapter 13 Inheritance
More informationChapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Chapter 13 Inheritance and Polymorphism CS 180 Sunil Prabhakar Department of Computer Science Purdue University Introduction Inheritance and polymorphism are key concepts of Object Oriented Programming.
More informationCSE 331 Software Design and Implementation. Lecture 14 Generics 2
CSE 331 Software Design and Implementation Lecture 14 Generics 2 Zach Tatlock / Spring 2018 Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping Using wildcards
More informationCSE 331 Software Design and Implementation. Lecture 14 Generics 2
CSE 331 Software Design and Implementation Lecture 14 Generics 2 James Wilcox / Winter 2016 Hi, I m James! Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping
More informationGenerics. IRS W-9 Form
Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]
More informationAnnouncements. Java Graphics. Exceptions. Java Odds & Ends
Java Odds & Ends Lecture 25 CS211 Fall 2005 Final Exam Wednesday, 12/14 9:00-11:30am Uris Aud Review Session Sunday, 12/11 1:00-2:30pm Kimball B11 Check your final exam schedule! Announcements For exam
More informationThe ArrayList class CSC 123 Fall 2018 Howard Rosenthal
The ArrayList class CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Describe the ArrayList class Discuss important methods of this class Describe how it can be used in modeling Much of the information
More informationThe list abstract data type defined a number of operations that all list-like objects ought to implement:
Chapter 7 Polymorphism Previously, we developed two data structures that implemented the list abstract data type: linked lists and array lists. However, these implementations were unsatisfying along two
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More informationExercise 8 Parametric polymorphism November 18, 2016
Concepts of Object-Oriented Programming AS 2016 Exercise 8 Parametric polymorphism November 18, 2016 Task 1 Consider the following Scala classes: class A class B extends A class P1[+T] class P2[T
More informationCS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.
CS61B Lecture #23 Announcements: Josh s office hours are now back in his office. HW6 now due Saturday. Partial solar eclipse tomorrow, starting at 1:52PM. Next one in August, 2017. See http://www.timeanddate.com/eclipse/list.html
More informationAgenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors Agenda
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationParametric polymorphism and Generics
Parametric polymorphism and Generics Today s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping.
More informationCS 251 Intermediate Programming Inheritance
CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?
More informationPIC 20A Collections and Data Structures
PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write
More informationDM550 / DM857 Introduction to Programming. Peter Schneider-Kamp
DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ ABSTRACT DATATYPES 2 Abstract Datatype (ADT)
More informationWeek 11. Abstract Data Types. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Week 11 Abstract Data Types CS 180 Sunil Prabhakar Department of Computer Science Purdue University Unknown input size Consider a program that has to read in a large number of names from input and print
More informationCS121/IS223. Object Reference Variables. Dr Olly Gotel
CS121/IS223 Object Reference Variables Dr Olly Gotel ogotel@pace.edu http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223
More informationStacks. Chapter 5. Copyright 2012 by Pearson Education, Inc. All rights reserved
Stacks Chapter 5 Copyright 2012 by Pearson Education, Inc. All rights reserved Contents Specifications of the ADT Stack Using a Stack to Process Algebraic Expressions A Problem Solved: Checking for Balanced
More informationReview: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object
Review: Diagrams for Inheritance - String makemodel - int mileage + (String, int) Class #3: Inheritance & Polymorphism Software Design II (CS 220): M. Allen, 25 Jan. 18 + (String, int) + void
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Up to here Not included in program Java collections framework prebuilt data structures interfaces and methods for manipulating
More informationIntroduction to Linked Data Structures
Introduction to Linked Data Structures A linked data structure consists of capsules of data known as nodes that are connected via links Links can be viewed as arrows and thought of as one way passages
More informationCSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA
CSE 3302 Lecture 7: Polymorphism and generics 16 September 2010 Nate Nystrom UTA 2 Polymorphism poly = many morph = shape Allow a variable to contain values with different types 3 Subtype polymorphism
More informationCS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1
CS61B Lecture #25: Java Generics Last modified: Thu Oct 19 19:36:29 2017 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.
More informationCOMP 401 Fall Recitation 7: Factories and Lists
COMP 401 Fall 2017 Recitation 7: Factories and Lists Agenda High-level introduction to Factories Factory Example/Exercise Introduction to Lists List Performance Exercise Quiz 2 Recitation Source Code Please
More informationInheritance. Improving Structure with Inheritance. Dr. Siobhán Drohan Mairead Meagher. Produced by:
Inheritance Improving Structure with Inheritance Produced by: Dr. Siobhán Drohan Mairead Meagher Department of Computing and Mathematics http://www.wit.ie/ Lectures and Labs This weeks lectures and labs
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Object-Oriented Programming Intro Department of Computer Science University of Maryland, College Park Object-Oriented Programming (OOP) Approach to improving software
More information5/23/2015. Core Java Syllabus. VikRam ShaRma
5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5
More informationgeneric programming alberto ferrari university of parma
generic programming alberto ferrari university of parma contents generic programming java generic programming methods & generic programming classes & generic programming java with generics generic methods
More informationContents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance
Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass
More informationCS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1
CS61B Lecture #25: Java Generics Last modified: Thu Oct 18 21:04:53 2018 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.
More informationAdvanced Programming Generics Collections
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
More informationJava Language Features
Java Language Features References: Object-Oriented Development Using Java, Xiaoping Jia Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From
More informationCISC370: Inheritance
CISC370: Inheritance Sara Sprenkle 1 Questions? Review Assignment 0 due Submissions CPM Accounts Sara Sprenkle - CISC370 2 1 Quiz! Sara Sprenkle - CISC370 3 Inheritance Build new classes based on existing
More informationNotes on access restrictions
Notes on access restrictions A source code file MyClass.java is a compilation unit and can contain at most one public class. Furthermore, if there is a public class in that file, it must be called MyClass.
More informationPIC 20A Number, Autoboxing, and Unboxing
PIC 20A Number, Autoboxing, and Unboxing Ernest Ryu UCLA Mathematics Last edited: October 27, 2017 Illustrative example Consider the function that can take in any object. public static void printclassandobj
More informationProblems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes
Problems Often you need the same behavior for different kind of classes Java Generics Use Object references to accommodate any object type Use Generic classes and Method The use of Object references induces
More informationLecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism
Lecture Outline Parametric Polymorphism and Java Generics Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards
More informationMIT AITI Lecture 18 Collections - Part 1
MIT AITI 2004 - Lecture 18 Collections - Part 1 Collections API The package java.util is often called the "Collections API" Extremely useful classes that you must understand to be a competent Java programmer
More informationOperators and Expressions
Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions
More informationSubclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented
Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and
More informationModule 11. Collections and Iterators. Adapted from Absolute Java, Rose Williams, Binghamton University
Module 11 Collections and Iterators Adapted from Absolute Java, Rose Williams, Binghamton University Parameterized Classes and Generics Beginning with version 5.0, Java allows class and method definitions
More informationGeneric classes & the Java Collections Framework. *Really* Reusable Code
Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers
More informationUMBC CMSC 331 Final Exam
UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy
More informationComputer Science 210 Data Structures Siena College Fall 2018
Computer Science 210 Data Structures Siena College Fall 2018 Topic Notes: The ArrayList Arrays are a very common method to store a collection of similar items. Arrays work very well for a lot of situations,
More informationCompilation 2009 Java 1.5 Features. Jan Midtgaard Michael I. Schwartzbach Aarhus University
Compilation 2009 Jan Midtgaard Michael I. Schwartzbach Aarhus University (That We Will Use) enums autoboxing improved for loop generic collections generic classes @override annotations covariant return
More informationGenerics, Type Safety, and Dynamic Data Structures
Generics, Type Safety, and Dynamic Data Structures 1 Reminders No classes, labs, recitations next week (gobble gobble) Consulting hours Monday only Project 8 (the final one!) is out start early Milestone
More informationJAVA V Assertions Java, winter semester
JAVA Assertions 1 Assertion since Java 1.4 the statement with a boolean expression a developer supposes that the expression is always satisfied (evaluates to true) if it is evaluated to false -> error
More informationCSE 8B Intro to CS: Java
CSE 8B Intro to CS: Java Winter, 2006 March 7 (Day 17) ArrayList Generics Class that: works like a resizable array ArrayList Has a current capacity: if you add more elements, it ll allocate more space
More informationCS 251 Intermediate Programming Methods and Classes
CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationCS 251 Intermediate Programming Methods and More
CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with
More informationGenerics in Java. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG
Generics in Java EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Motivating Example: A Book of Objects 1 class Book { 2 String[] names; 3 Object[] records; 4 /* add a name-record
More informationMotivating Example: Observations (1) Generics in Java. Motivating Example: A Book of Objects. Motivating Example: Observations (2)
Motivating Example: Observations (1) Generics in Java EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG In the Book class: By declaring the attribute Object[] records We meant that
More informationGeneric Collections. Chapter The Object class
Chapter 13 Generic Collections Goals Introduce class Object and inheritance Show how one collection can store any type of element using Object[] 13.1 The Object class The StringBag class shown of Chapter
More informationAgenda. Objects and classes Encapsulation and information hiding Documentation Packages
Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics
More informationJava Collections Framework
Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several
More information1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8
Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(
More informationImplementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations
Readings List Implementations Chapter 20.2 Objectives Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Additional references:
More informationJava Programming Training for Experienced Programmers (5 Days)
www.peaklearningllc.com Java Programming Training for Experienced Programmers (5 Days) This Java training course is intended for students with experience in a procedural or objectoriented language. It
More informationIntroduction to Generics in Java 5
Introduction to Generics in Java 5 One trouble with the list, stack, and queue ADTs that we have written so far is that the type of the objects stored in them cannot be checked at compile time. For example,
More information9 Working with the Java Class Library
9 Working with the Java Class Library 1 Objectives At the end of the lesson, the student should be able to: Explain object-oriented programming and some of its concepts Differentiate between classes and
More informationUnit5: Packages and abstraction. Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15
Unit5: Packages and abstraction Prepared by: Dr. Abdallah Mohamed, AOU-KW Updated by Mrs. Malak EL-Amir AOU SAB Fall 14-15 1 1. Introduction 2. Java libraries 3. The documentation of standard packages
More informationThe Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss
The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,
More informationCMSC 202. Containers
CMSC 202 Containers Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects. Arrays are compiler-supported containers.
More informationPractice for Chapter 11
Practice for Chapter 11 MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) Object-oriented programming allows you to derive new classes from existing
More informationCore Java - SCJP. Q2Technologies, Rajajinagar. Course content
Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code
More informationIntroduction to Java Written by John Bell for CS 342, Spring 2018
Introduction to Java Written by John Bell for CS 342, Spring 2018 Based on chapters 1 to 6 of Learning Java by Patrick Niemeyer and Daniel Leuck, with additional material from other sources. History I
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationLanguage Features. 1. The primitive types int, double, and boolean are part of the AP
Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are
More informationChapter 10. Arrays. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Chapter 10 Arrays CS 180 Sunil Prabhakar Department of Computer Science Purdue University Objectives After this week, you should be able to Manipulate a collection of data values, using an array. Declare
More informationGrouping Objects (I)
KTH ROYAL INSTITUTE OF TECHNOLOGY Stockholm Sweden Grouping Objects (I) Managing collections of objects Ric Glassey glassey@kth.se Main concepts to be covered Grouping Objects Using ArrayLists Looping
More informationCollections, Maps and Generics
Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.
More informationPARAMETRIC POLYMORPHISM
PARAMETRIC POLYMORPHISM Java C#! Parametric polymorphism: " Java Generics and Generic C# for.net! The idea: the compiler is able to check parametric classes just looking at their definilon 1 Java Generics
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationCasting -Allows a narrowing assignment by asking the Java compiler to "trust us"
Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:
More informationAP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested.
AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested. 1. The Nose class... b) will not compile because the m1 method parameter should be named n, not x. 2. The Ears class...
More informationCSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation Hal Perkins Winter 2018 Generics UW CSE 331 Winter 2018 1 Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1
More informationCSE 331. Generics (Parametric Polymorphism)
CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/ 1 Parametric polymorphism
More information