Generics, Type Safety, and Dynamic Data Structures
|
|
- Laureen Shelton
- 6 years ago
- Views:
Transcription
1 Generics, Type Safety, and Dynamic Data Structures 1
2 Reminders No classes, labs, recitations next week (gobble gobble) Consulting hours Monday only Project 8 (the final one!) is out start early Milestone due 11/28 Final project due 12/5 Armand's Discussion section Cancelled next week 2
3 Project 7 Design Use object oriented design! Load method should handle much of the labyrinth processing to make rest of methods easier char[][] and String[] insufficient still need to process structure of labyrinth later on in every other method (ouch!) Organize information in classes Labyrinth classes (pros/cons?) Cell classes (pros/cons?) Wall classes (pros/cons?) 3
4 Today s Recitation Collections Java generics Parameterized classes and methods Compiler provides type safety Syntax and semantics Examples Generics Examples 4
5 Collections Collection Serves as a repository for other objects Array, LinkedList, etc. Java Collections Framework Provides a unified interface for working with collections 5
6 Java Collections Framework Interfaces List Most basic collection Set No Duplicates SortedSet No Duplicates Sorted order Map Key, value pairs SortedMap Key, value pairs Sorted Order Implementations ArrayList An expandable array Vector An expandable array Stack FILO TreeMap A Map Sorted 6
7 Collection Design: Keep collections general so that they can hold any type of object Java 5.0 provides generics Allows type of collection to be established upon instantiation 7
8 Queues Java provides a Queue interface FIFO data structure As a linked list As an array Methods boolean offer(e o) E peek() E element() E poll() E remove() // insert element to end of queue // retreive front element of queue // same as peek, but with exceptions // remove and return front element of queue // same as poll, but with exceptions 8
9 Building Your Own List Node class Item Next pointer Type unsafe Class Object supports any class type Should use parameterized type! public class Node { private Object data; private Node next; next) { { data) { public Node(Object data, Node this.data = data; this.next = next; public void setnext(node next) this.next = next; public void setdata(object this.data = data; public Node getnext() { return next; public Object getdata() { return data; 9
10 Java Generics: Key Idea Parameterize type definitions Parameterized classes and methods Provide type safety Compiler performs type checking Prevent runtime cast errors 10
11 Cast Exceptions at Runtime public class OldBox { Object data; public OldBox( Object data ) { this.data = data; public Object getdata() { return data; OldBox intbox = new OldBox( 42 ); int x = (Integer) intbox.getdata(); OldBox strbox = new OldBox( Hi ); String s = (String) strbox.getdata(); int y = (Integer) strbox.getdata(); intbox = strbox; ClassCastException! Compiles but fails at runtime 11
12 Naïve Solution public class IntBox { Integer data; public IntBox( Integer data ) { this.data = data; public Integer getdata() { return data; IntBox intbox = new IntBox( 42 ); int x = intbox.getdata(); StrBox strbox = new StrBox( Hi ); String s = strbox.getdata(); int y = (Integer) strbox.getdata(); intbox = strbox; Errors caught by compiler public class StrBox { String data; public StrBox( String data ) { this.data = data; public String getdata() { return data; public class FooBox { Foo data; public FooBox( Foo data ) { this.data = data; public Foo getdata() { return data; Infinite many classes possible 12
13 Parameterized Classes public class OldBox { Object data; public OldBox( Object data ) { this.data = data; public Object getdata() { return data; We want the box to hold a specific class abstractly represented Object does not work as we have seen earlier Solution parameterize the class definition public class Box<E> { E data; public Box( E data ) { this.data = data; public E getdata() { return data; E refers to a particular type The constructor takes an object of type E, not any object To use this class, E must be replaced with a specific class 13
14 How to Use Parameterized Classes public class Box<E> { E data; public Box( E data ) { this.data = data; public E getdata() { return data; Box<Integer> intbox = new Box<Integer>( 42 ); int x = intbox.getdata();//no cast needed Box<String> strbox = new Box<String>( Hi ); String s = strbox.getdata();//no cast needed Following lines will not compile anymore: String s = (String) intbox.getdata(); int y = (Integer) strbox.getdata(); intbox = strbox; Runtime errors now converted to compile time errors 14
15 When to Use Parameterized Classes Particularly useful for container classes Containers hold but do not process data All collections framework classes in Java 5.0 defined using generics See the Java 5.0 API documentation 15
16 Parameterized Classes: Syntax A class can have multiple parameters, e.g: public class Stuff<A,B,C> { Subclassing parameterized classes allowed, e.g: /* Extending a particular type */ class IntBox extends Box<Integer> { Or /* Extending a parameterized type */ class SpecialBox<E> extends Box<E> { SpecialBox<String> is a subclass of Box<String>. /* Following assignment is legal */ Box<String> sb = new SpecialBox<String>( Hi ); 16
17 Parameterized Classes in Methods A parameterized class is a type just like any other class. It can be used in method input types and return types, e.g: Box<String> amethod( int i, Box<Integer> b ) { If a class is parameterized, that type parameter can be used for any type declaration in that class, e.g: public class Box<E> { E data; public Box( E data ) { this.data = data; public E getdata() { return data; public void copyfrom( Box<E> b ) { this.data = b.getdata(); //We have added an infinite number of types of Boxes //by writing a single class definition 17
18 Bounded Parameterized Types Sometimes we want restricted parameterization of classes. We want a box, called MathBox that holds only Number objects. We can t use Box<E> because E could be anything. We want E to be a subclass of Number. public class MathBox<E extends Number> extends Box<Number> { public MathBox( E data ) { super( data ); public double sqrt() { return Math.sqrt( getdata().doublevalue() ); 18
19 Bounded Parameterized Types (. Contd ) public class MathBox<E extends Number> extends Box<Number> { public MathBox( E data ) { super( data ); public double sqrt() { return Math.sqrt( getdata().doublevalue() ); The <E extends Number> syntax means that the type parameter of MathBox must be a subclass of the Number class. We say that the type parameter is bounded. new MathBox<Integer>( 5 );//Legal new MathBox<Double>( 32.1 );//Legal new MathBox<String>( No good! );//Illegal 19
20 Parameterized Methods Consider the following class: public class Foo { //Foo is not parameterized public <T> T amethod( T x ) { //will not compile without <T> //to indicate that this is a //parameterized method. return x; public static void main( String[] args ) { Foo foo = new Foo(); int k = foo.amethod( 5 ); String s = foo.amethod( "abc" ); public class Bar<T> { //Bar is parameterized public T amethod( T x ) { return x; public static void main( String[] args ) { Bar<Integer> bar = new Bar<Integer>(); int k = bar.amethod( 5 ); String s = bar.amethod( "abc" ); //Compilation error here Fix foo and vary parameter to () amethod Once Bar<T> object is fixed, we are locked to a specific T. 20
21 Generics Examples Stack HashMap List 21
22 Stack Using Generics Without Generics class Stack { void push( Object o ) {... Object pop() { String s = "Hello"; Stack st = new Stack();... st.push( s );... s = (String) st.pop(); With Generics class Stack<A> { void push( A a ) {... A pop() { String s = "Hello"; Stack<String> st = new Stack<String>(); st.push( s );... s = st.pop(); 22
23 Collections Example HashMap<Intger, String> sumnerfavfive = new HashMap<Intger, String>(); sumnerfavfive.put(1, Magic Labyrinths ); sumnerfavfive.put(2, Happy Dogs ); sumnerfavfive.put(3, Blue Beanies ); sumnerfavfive.put(4, Huzzah! ); sumnerfavfive.put(5, CS180 Students ); String SumnerFavorite = sumnerfavfive.get(1); Note: Hashmap_1.4 hm => Hashmap_1.5<Object, Object> 23
24 List Using Generics List<String> ys = new LinkedList<String>(); ys.add( "zero" ); List<List<String>> yss; yss = new LinkedList<List<String>>(); yss.add( ys ); String y = yss.iterator().next().iterator().next(); // Compile-time error much better! Integer z = ys.iterator().next(); 24
25 Quiz Given the following class signature, what type of objects can the parameterized type T support? public class Quiz<T extends Comparable<T>> { 25
Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes
Java Generics 1 Concepts Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes 2 What Are Generics? Generics
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 informationCS/ENGRD 2110 SPRING 2018
CS/ENGRD 2110 SPRING 2018 Lecture 7: Interfaces and http://courses.cs.cornell.edu/cs2110 1 2 St Valentine s Day! It's Valentines Day, and so fine! Good wishes to you I consign.* But since you're my students,
More informationBuilding Java Programs
Building Java Programs Chapter 16 References and linked nodes reading: 16.1 2 Recall: stacks and queues stack: retrieves elements in reverse order as added queue: retrieves elements in same order as added
More informationCMPSCI 187 Midterm 1 (Feb 17, 2016)
CMPSCI 187 Midterm 1 (Feb 17, 2016) Instructions: This is a closed book, closed notes exam. You have 120 minutes to complete the exam. The exam has 10 pages printed on double sides. Be sure to check both
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 informationCSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm
CSC 172 Data Structures and Algorithms Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm Agenda Administrative aspects Java Generics Chapter 1 ADMINISTRATIVE ASPECTS Workshops Workshops Workshops begin on this
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 informationBuilding Java Programs
Building Java Programs Chapter 16 References and linked nodes reading: 16.1 2 Value semantics value semantics: Behavior where values are copied when assigned, passed as parameters, or returned. All primitive
More informationCS24 Week 4 Lecture 2
CS24 Week 4 Lecture 2 Kyle Dewey Overview Linked Lists Stacks Queues Linked Lists Linked Lists Idea: have each chunk (called a node) keep track of both a list element and another chunk Need to keep track
More informationCS2113 Lab: Collections 10/29/2018
CS2113 Lab: Collections Yawei Wang 10/29/2018 Install and Use IntelliJ on Mac or Window If you haven t installed JDK before, go to https://www.oracle.com/technetwork/java/javaseproducts/downloads/in dex.html
More informationGenerics in Java and Beyond
Generics in Java and Beyond Martin Buechi 2001 by Martin Büchi 1 Overview Generics Abstraction of generic concepts. C++ templates (STL), parameterized types, ML polymorphic data types and functions, Beta
More informationCS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes
CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.
More informationCS 314 Midterm 2 Fall 2012
Points off 1 2 3 4 5 Total off Net Score CS 314 Midterm 2 Fall 2012 Your Name_ Your UTEID Circle yours TA s name: John Zihao Instructions: 1. There are 5 questions on this test. 2. You have 2 hours to
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 informationEXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS
T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 Trimester 2, MID-TERM TEST COMP103 Introduction
More informationTwo Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.
Class #07: Java Primitives Software Design I (CS 120): M. Allen, 13 Sep. 2018 Two Types of Types So far, we have mainly been dealing with objects, like DrawingGizmo, Window, Triangle, that are: 1. Specified
More informationToday. Instance Method Dispatch. Instance Method Dispatch. Instance Method Dispatch 11/29/11. today. last time
CS2110 Fall 2011 Lecture 25 Java program last time Java compiler Java bytecode (.class files) Compile for platform with JIT Interpret with JVM Under the Hood: The Java Virtual Machine, Part II 1 run native
More informationCS 307 Final Spring 2008
Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2008 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to
More informationAnnouncements/Follow-ups
Announcements/Follow-ups Midterm 2 graded Average was 52/80 (63%), Std. Dev. was 12 P5 and Lab8 P5 due tomorrow Very light Lab8 Practice with collections Due at end of lab period P6 posted tomorrow Due
More informationModulo I Java Generics
Modulo I Java Generics Prof. Ismael H F Santos April 05 Prof. Ismael H. F. Santos - ismael@tecgraf.puc-rio.br 1 Ementa Modulo I - Tópicos em JAVA Generics (incompleto!) April 05 Prof. Ismael H. F. Santos
More informationLecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University
Lecture 6 COMP1006/1406 (the OOP course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments A1,A2,A3 are all marked A4 marking just started A5 is due Friday, A6 is due Monday a quick
More informationDistributed Systems Recitation 1. Tamim Jabban
15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming
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 informationWhy Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types
Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types generics enable types (classes and interfaces) to be parameters when defining
More information11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.
JAVA GENERICS Lecture CS110 Fall 018 Photo credit: Andrew Kennedy Java Collections Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob */ boolean
More informationMidterm Exam CS 251, Intermediate Programming March 6, 2015
Midterm Exam CS 251, Intermediate Programming March 6, 2015 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible
More informationDistributed Systems Recitation 1. Tamim Jabban
15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming
More information17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know
Organizing Data Data Structures that we know 17 Java Collections Generic Types, Iterators, Java Collections, Iterators Today: Arrays Fixed-size sequences Strings Sequences of characters Linked Lists (up
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 informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationPhoto credit: Andrew Kennedy JAVA GENERICS
Photo credit: Andrew Kennedy JAVA GENERICS Lecture 17 CS2110 Spring 2017 Java Collections 2 Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob
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 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 informationAdvanced Java Concepts Unit 3: Stacks and Queues
Advanced Java Concepts Unit 3: Stacks and Queues Stacks are linear collections in which access is completely restricted to just one end, called the top. Stacks adhere to a last-in, first-out protocol (LIFO).
More information+ Abstract Data Types
Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract
More informationCOURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE
COURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Generics Defining a generic Run-time behavior Collections List Set Map COUSE CONTENT Collections Utilities classes Aggregate Operations
More informationFamily Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013
Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Model Solutions COMP 103: Test
More informationDay 6. COMP1006/1406 Summer M. Jason Hinek Carleton University
Day 6 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 3 is due on Monday a quick look back abstract classes and interfaces casting objects abstract data
More informationCosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs
1 Cosc 241 Programming and Problem Solving Lecture 9 (26/3/18) Collections and ADTs Michael Albert michael.albert@cs.otago.ac.nz Keywords: abstract data type, collection, generic class type, stack 2 Collections
More informationCS 307 Midterm 2 Spring 2011
Points off 1 2 3 4 5 Total off Net Score Exam Number: CS 307 Midterm 2 Spring 2011 Name UTEID login name TA's Name: Dan Muhibur Oliver (Circle One) Instructions: 1. Please turn off your cell phones and
More informationToday. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1
Today Book-keeping Exceptions Subscribe to sipb-iap-java-students Collections http://sipb.mit.edu/iap/java/ Play with problem set 1 No class Monday (MLK); happy Hunting Problem set 2 on Tuesday 1 2 So
More informationData Structure. Recitation IV
Data Structure Recitation IV Topic Java Generics Java error handling Stack Lab 2 Java Generics The following code snippet without generics requires casting: List list = new ArrayList(); list.add("hello");
More informationGeneric programming in OO Languages
CS 242 2012 Generic programming in OO Languages Reading Text: Sections 9.4.1 and 9.4.3 J Koskinen, Metaprogramming in C++, Sections 2 5 Gilad Bracha, Generics in the Java Programming Language Questions
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 informationCS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes
1 CS/ENGRD 2110 FALL 2016 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 Announcements 2 Attendance for this week s recitation is mandatory! A2 is due Today Get started
More informationName Section Number. CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice
Name Section Number CS210 Exam #2 *** PLEASE TURN OFF ALL CELL PHONES*** Practice All Sections Bob Wilson OPEN BOOK / OPEN NOTES You will have all 90 minutes until the start of the next class period. Spend
More informationLinked Lists. References and objects
Linked Lists slides created by Marty Stepp http://www.cs.washington.edu/143/ Modified by Sarah Heckman Reading: RS Chapter 16 References and objects In Java, objects and arrays use reference semantics.
More informationGenerics and Type Safety. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Generics and Type Safety CS 180 Sunil Prabhakar Department of Computer Science Purdue University Dynamic Data Collections Already seen several examples of dynamic data Linked list, Stack, Queue, Trees
More informationLinked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }
Linked Lists Since a variable referencing an object just holds the address of the object in memory, we can link multiple objects together to form dynamic lists or other structures. In our case we will
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 informationCMP Points Total Midterm Spring Version (16 Points) Multiple Choice:
CMP-338 106 Points Total Midterm Spring 2017 Version 1 Instructions Write your name and version number on the top of the yellow paper. Answer all questions on the yellow paper. One question per page. Use
More informationcs Java: lecture #6
cs3101-003 Java: lecture #6 news: homework #5 due today little quiz today it s the last class! please return any textbooks you borrowed from me today s topics: interfaces recursion data structures threads
More informationFinal Exam CS 251, Intermediate Programming December 13, 2017
Final Exam CS 251, Intermediate Programming December 13, 2017 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible
More informationcsci 210: Data Structures Stacks and Queues
csci 210: Data Structures Stacks and Queues 1 Summary Topics Stacks and Queues as abstract data types ( ADT) Implementations arrays linked lists Analysis and comparison Applications: searching with stacks
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 information36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini
36. Collections Java Summer 2008 Instructor: Dr. Masoud Yaghini Outline Introduction Arrays Class Interface Collection and Class Collections ArrayList Class Generics LinkedList Class Collections Algorithms
More informationWhat are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods
What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods 6 Defining the idea Behind Java Generics Data Types are now used as TypeParameters 7 Defining the idea Behind Java
More informationCS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes
CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method
More informationMore Data Structures (Part 1) Stacks
More Data Structures (Part 1) Stacks 1 Stack examples of stacks 2 Top of Stack top of the stack 3 Stack Operations classically, stacks only support two operations 1. push 2. pop add to the top of the stack
More informationCS 307 Final Fall 2009
Points off 1 2 3 4 5 6 Total off Net Score CS 307 Final Fall 2009 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 6 questions on this test. 3. You have 3 hours to
More informationCOMP 103 : Test. 2018, Sept 12//(Corrected) ** WITH SOLUTIONS
Family Name:.............................. Other Names:............................. Student ID:................................ Signature.................................. COMP 103 : Test 2018, Sept 12//(Corrected)
More informationCS 307 Final Spring 2009
Points off 1 2 3 4 5 Total off Net Score CS 307 Final Spring 2009 Name UTEID login name Instructions: 1. Please turn off your cell phones. 2. There are 5 questions on this test. 3. You have 3 hours to
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 informationSelected Java Topics
Selected Java Topics Introduction Basic Types, Objects and Pointers Modifiers Abstract Classes and Interfaces Exceptions and Runtime Exceptions Static Variables and Static Methods Type Safe Constants Swings
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 informationData Structures. BSc in Computer Science University of New York, Tirana. Assoc. Prof. Marenglen Biba 1-1
Data Structures BSc in Computer Science University of New York, Tirana Assoc. Prof. Marenglen Biba 1-1 General info Course : Data Structures (3 credit hours) Instructor : Assoc. Prof. Marenglen Biba Office
More informationUNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED
UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED EXERCISE 11.1 1. static public final int DEFAULT_NUM_SCORES = 3; 2. Java allocates a separate set of memory cells in each instance
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 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 informationCS 1322 Test 2 - Version 1 Tuesday June 24 th
Name: GT Number: TA: Commenting your code on this test is optional, however it may help the grader understand your code better. Other style issues such as using good variables names and using abstraction
More informationEXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS
T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2012 Trimester 1, MID-TERM TEST COMP103 Introduction
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 informationCOURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE
COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate
More informationCS 302 ALGORITHMS AND DATA STRUCTURES
CS 302 ALGORITHMS AND DATA STRUCTURES A famous quote: Program = Algorithm + Data Structure General Problem You have some data to be manipulated by an algorithm E.g., list of students in a school Each student
More informationCS 310: Array- and Linked-based Data Structures
CS 310: Array- and Linked-based Data Structures Chris Kauffman Week 3-2 Logistics At Home Read Weiss Ch 15: ArrayList implementation Read Weiss Ch 16: Stacks and Queues implementation HW 1: Due Sunday
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 informationCS24 Week 4 Lecture 1
CS24 Week 4 Lecture 1 Kyle Dewey Overview Additional use of const in C++ List ADT Array Lists Linked Lists Additional Use of const We ve seen const already in two positions: What is pointed to is constant
More informationMidterm Exam 2 CS 455, Spring 2011
Name: USC loginid (e.g., ttrojan): Midterm Exam 2 CS 455, Spring 2011 March 31, 2011 There are 6 problems on the exam, with 50 points total available. There are 7 pages to the exam, including this one;
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 informationCOMP 103 : Test. 2018, Sept 12//(Corrected)
Family Name:.............................. Other Names:............................. Student ID:................................ Signature.................................. COMP 103 : Test 2018, Sept 12//(Corrected)
More informationLinked Lists. Chapter 12.3 in Savitch
Linked Lists Chapter 12.3 in Savitch Preliminaries n Arrays are not always the optimal data structure: q An array has fixed size needs to be copied to expand its capacity q Adding in the middle of an array
More informationJava Review: Objects
Outline Java review Abstract Data Types (ADTs) Interfaces Class Hierarchy, Abstract Classes, Inheritance Invariants Lists ArrayList LinkedList runtime analysis Iterators Java references 1 Exam Preparation
More informationCS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12
CS 151 Linked Lists, Recursively Implemented 1 2 Linked Lists, Revisited Recall that a linked list is a structure that represents a sequence of elements that are stored non-contiguously in memory. We can
More informationCrash Course Review Only. Please use online Jasmit Singh 2
@ Jasmit Singh 1 Crash Course Review Only Please use online resources @ Jasmit Singh 2 Java is an object- oriented language Structured around objects and methods A method is an action or something you
More informationUniversity of Maryland College Park Dept of Computer Science
University of Maryland College Park Dept of Computer Science CMSC132H Fall 2009 Midterm First Name (PRINT): Last Name (PRINT): University ID: I pledge on my honor that I have not given or received any
More informationCMP Points Total Midterm Spring Version (16 Points) Multiple Choice:
Version 1 Instructions Write your name and version number on the top of the yellow paper. Answer all questions on the yellow paper. One question per page. Use only one side of the yellow paper. 1. (16
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 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 informationUniversity of Maryland College Park Dept of Computer Science
University of Maryland College Park Dept of Computer Science CMSC132H Fall 2009 Midterm Key Problem 1 (12 pts) Algorithmic Complexity 1. (6 pts) Calculate the asymptotic complexity of the code snippets
More informationAdvanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II
Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic
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 informationFundamental language mechanisms
Java Fundamentals Fundamental language mechanisms The exception mechanism What are exceptions? Exceptions are exceptional events in the execution of a program Depending on how grave the event is, the program
More informationCS2110 Fall 2011 Lecture 25. Under the Hood: The Java Virtual Machine, Part II
CS2110 Fall 2011 Lecture 25 Under the Hood: The Java Virtual Machine, Part II 1 Java program last time Java compiler Java bytecode (.class files) Compile for platform with JIT Interpret with JVM run native
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 informationCSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community
CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring
More informationObject Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia
Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing
More informationGeneralized Code. Fall 2011 (Honors) 2
CMSC 202H Generics Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using base classes is general, but restricted to a single class hierarchy
More information