DrStrangebrac<E,T> Or how I learned to stop worrying, and love generics...

Size: px
Start display at page:

Download "DrStrangebrac<E,T> Or how I learned to stop worrying, and love generics..."

Transcription

1 DrStrangebrac<E,T> Or how I learned to stop worrying, and love generics... a presentation to The Seattle Java Users Group by Wilhelm Fizpatrick Java is Sun Microsystems, all other trademarks are the property of their owners

2 Java a few changes Significance Annotations Generics Autoboxing Varargs Enhanced for Loop Enumerations Static Imports Intrusiveness Generics Autoboxing Varargs Enumerations Annotations Enhanced for Loop Static Imports The first major change to the language since 1.1 (who remembers assert?)

3 Generics: Significantly Intrusive Already in use in the standard libraries 41 classes and 19 interfaces are now generic (out of 3500) In java.lang, java.lang.reflect, java.lang. ref, java.util, java.util.concurrent, java. security, javax.naming Being retrofitted onto many extension APIs Hard to say I ll ignore them for now

4 public static <T extends Object & Comparable<? super T>> T What s Going On Here?!? max(collection<? extends T> coll) [Generics are] the most monstrously conceived and dangerous communist plot we have ever had to face General Jack D. Ripper (paraphrased) We had a nice cosy little language going, and somebody snuck in and added all these angle brackets to it! Do we need them? They are not only possible, they are essential! Dr. Strangebrac<E,T>

5 Don t Panic! Survival Kit Strange syntax in the JavaDoc? Ignore everything between the <angle brackets> Read single capital letters (E, T, K, V) as Object For example: public static <T extends Object & Comparable<? super T>> T max(collection<? extends T> coll) can be read as public static Object max(collection coll)

6 Survival Kit Ignore the unchecked warning: Note: Test.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Disable it if you like: javac -Xlint:-unchecked MyCode.java Live life much as you always did...

7 Business As Usual public class Business { public static void main( String[] args ) { List l = new ArrayList(); l.add( "foo" ); l.add( "qux" ); l.add( "bar" ); System.out.println(Collections.max( l )); } } $ javac Business.java Note: Business.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. $ java Business qux

8 Questions?

9 What are Generics Anyway? Generic programming is a distinct approach to program design, on a par with procedural, object-oriented, or functional approaches "My working definition of generic programming is "programming with concepts," where a concept is defined as a family of abstractions that are all related by a common set of requirements." David R. Musser, generic programming researcher "Generic programming is a programming method that is based in finding the most abstract representations of efficient algorithms." Alexander Stepanov, C++ STL Author Generic programming focuses on describing algorithms independent of the type of data on which they operate

10 Why Not Use Assembly? Back when programmers coded to the metal, we didn t talk about types we just operated on the data Sounds perfect for generic programming! But what happens when you perform the right operation on the wrong data? We d like our language to catch these things

11 Type Checking Static Type Checking At compile time, based on information in the source C++, Pascal, Haskell Dynamic Type Checking While the program runs, by tagging data elements with their type Python, Ruby, Scheme

12 Java: static or dynamic? Both! The compiler performs type checking, but The programmer can override the compiler, so The runtime also performs type checking The compiler and the runtime each detect problems the other cannot

13 Java s Static Type Checking Statically detected type errors Are found sooner at compile time Won t crash a running program But... We have to help the compiler by declaring our types The compiler can t help us if we keep our data in generic variables: Object o = "10/19/2004"; ((Date)o).getYear();

14 Who Does That? Us, every day... We just disguise it better: Set appointments = new HashSet(); appointments.add( "10/19/2004" );... Iterator i = appointments.iterator(); ((Date)i.next()).getYear(); This is called the generic idiom (when we get it right)

15 Java Generics Java generics are an extension of Java s static type checking system Generic types exist only at compile time, they have no existence at runtime They allow us to be more confident in our use of the generic idiom

16 Improved Survival Kit Learn enough about those angle brackets and capital letters to understand what the JavaDoc is trying to tell you Declare and use parameterized types from the standard library Strive to eliminate unchecked warnings Compile with -Xlint:unchecked

17 Unchecked Warnings An unchecked warning means the compiler can t prove your code is typesafe... $ javac -Xlint:unchecked Business.java Business.java:7: warning: [unchecked] unchecked call to add(e) as a member of the raw type java.util.list l.add( "foo" ); ^ Business.java:8: warning: [unchecked] unchecked call to add(e) as a member of the raw type java.util.list l.add( "qux" ); ^ Business.java:9: warning: [unchecked] unchecked call to add(e) as a member of the raw type java.util.list l.add( "bar" ); ^...

18 Unchecked Warnings... ^ Business.java:10: warning: [unchecked] unchecked conversion found : java.util.list required: java.util.collection<? extends T> System.out.println(Collections.max( l )); ^ Business.java:10: warning: [unchecked] unchecked method invocation: <T>max(java.util.Collection<? extends T>) in java.util.collections is applied to (java.util.list) System.out.println(Collections.max( l )); ^ 5 warnings The compiler doesn t have enough information But it still must compile old code

19 Type Safety (according to Java) If a program compiles with no errors or warnings Then it will produce no unexpected type errors at runtime (ClassCastException) When is a type error expected? When the programmer explicitly overrides the compiler (inserts an cast)

20 Help the Compiler Help You To give the compiler the information it needs, we must talk about types abstractly To talk about data abstractly, we use parameters: int add( int a, int b ) { return a + b } Then we bind them to concrete values: add( 3, 6 )

21 Type Variables So let s do the same for types declare: interface Map<K,V> { void put( K key, V value ); V get( K key ); } And bind: Map<String,Date> appointments =... interface Map<String,Date> { void put( String key, Date value ); Date get( String key ); }

22 Naming Conventions A type variable can be any Java identifier But a single capital letter is preferred E for elements of a collection K and V for keys and values T, U, and V for types with no specific semantics Probably at most two or three per class

23 Terminology Alert When we say Map<String,Date> We are said to have instantiated a generic (also known as a parameterized) type But a type instance only exists at compile time Object instantiation and type instantiation are two different concepts with the same name!

24 New Business public class Business { public static void main( String[] args ) { List<String> l = new ArrayList<String>(); l.add( "foo" ); l.add( "qux" ); l.add( "bar" ); System.out.println(Collections.max( l )); } } $ javac -Xlint:unchecked Business.java $ java Business qux

25 What s New is Old Again $ javap -c Business Compiled from "Business.java" public class Business extends java.lang.object{... public static void main(java.lang.string[]); Code: 0: new #2; //class java/util/arraylist 3: dup 4: invokespecial #3; //Method java/util/arraylist."<init>":()v 7: astore_1 8: aload_1 9: ldc #4; //String foo 11: invokeinterface #5, 2; //InterfaceMethod java/util/list.add:(ljava/lang/object;)z... 38: aload_1 39: invokestatic #9; //Method java/util/collections.max:(ljava/util/collection;)ljava/lang/object; 42: checkcast #10; //class java/lang/string...

26 No Generics at Runtime Generic types are purely a feature of Java s static (compile time) type checking They are stripped away in the bytecode the fancy term for this is type erasure Thus, generic types can t be seen at runtime: List<Date> ld = new ArrayList<Date>(); List<String> ls = new ArrayList<String>(); System.out.println( ld.getclass() == ls.getclass() ); true

27 Why are Generic Collections a Good Thing? Type parameters act as documentation the compiler can act on: public void addnames( Set<String> names ); public Map<Date,Location> getappointments(); Fewer manual casts mean fewer mistakes: Date d = ld.get( 3 ); Arrays provide only one abstract data type, the list or sequence

28 Generics and Inheritance Will this compile? type inheritance applies List<Object> lo = new ArrayList<Date>(); Nope... no type inheritance RuntimeType.java:9: incompatible types found : java.util.arraylist<java.util.date> required: java.util.list<java.lang.object> List<Object> lo = new ArrayList<Date>(); Type parameters have no implicit super/sub type relationship

29 Why Not? Consider this: List<Date> ld = new ArrayList<Date>(); List<Object> od = ld; o1.add( "no typesafety today!" ); Date d = ld.get( 0 ); // Boom! Type safety would be violated Therefore the compiler doesn t allow it

30 Arrays Did It Differently Compiles fine... Date[] ad = new Date[5]; Object[] od = ad; od[0] = "type safety rides again!"; Date d = ad[0];...but at runtime: Exception in thread "main" java.lang.arraystoreexception: java.lang.string at ArrayTest.main(ArrayTest.java:7) Generic types don t exist at runtime, so they cannot make the same bargain

31 Okay, Now What? public void printall( Collection<Object> os ) { for( Object o: os ) System.out.println( o ); } List<String> l = new ArrayList<String>(); l.add( "one" ); l.add( "two" ); printall( l ); $ javac -Xlint:unchecked Wildcard1.java Wildcard1.java:8: printall(java.util.collection<java.lang.object>) in Wildcard1 cannot be applied to (java.util.list<java.lang.string>) printall( l );

32 Alright, How About... public void printall( Collection os ) { for( Object o: os ) System.out.println( o ); } List<String> l = new ArrayList<String>(); l.add( "one" ); l.add( "two" ); printall( l ); $ javac -Xlint:unchecked Wildcard1.java $ java Wildcard1 one two

33 But Now We Can... public void printall( Collection os ) { for( Object o: os ) System.out.println( o ); os.add( new Date ); // poisoning the well } List<String> l = new ArrayList<String>(); l.add( "one" ); l.add( "two" ); printall( l ); $ javac -Xlint:unchecked Wildcard1.java Wildcard1.java:13: warning: [unchecked] unchecked call to add(e) as a member of the raw type java.util.collection os.add( new Date() ); 1 warning

34 And The Final Answer Is... public void printall( Collection<?> os ) { for( Object o: os ) System.out.println( o ); os.add( new Date ); // poisoning the well } List<String> l = new ArrayList<String>(); l.add( "one" ); l.add( "two" ); printall( l ); $ javac -Xlint:unchecked Wildcard1.java Wildcard1.java:13: add(capture of?) in java.util.collection <capture of?> cannot be applied to (java.util.date) os.add( new Date() ); 1 error

35 The Wildcard (?)? can be read as unknown type The compiler restricts what may be done with type variable bound to? List<?> l = new ArrayList<String>; It may be a return type (and is treated as Object) Object o = l.get(0); But not a method parameter type: l.add( foo ); //error

36 Object vs? Object is a concrete type that happens to be the root type in Java's type hierarchy It has meaning at both compile and run time? is the "unknown type" it can stand in for any type but the set of operations that can be performed with it are restricted? only has meaning at compile time

37 Collection<Object> vs Collection<?> vs Collection Collection<Object> is a collection of heterogeneous instances of potentially no common type Collection<?> is a collection of homogeneous instances of some common types we just don t know what that common type is Collection is a raw type unless we are dealing with legacy code, we should avoid it

38 A Problem With? interface Shape { void draw(); } class Circle implements Shape { public void draw() {} } void drawall( Collection<?> ss ) { for( Object s: ss ) s.draw(); } List<Circle> lc = new ArrayList<Circle>(); drawall( lc ); $ javac -Xlint:unchecked Shapes.java Shapes.java:20: cannot find symbol symbol : method draw() location: class java.lang.object for( Object s: ss ) s.draw();

39 Binding? interface Shape { void draw(); } class Circle implements Shape { public void draw() {} } void drawall( Collection<? extends Shape> ss ) { for( Shape s: ss ) s.draw(); } List<Circle> lc = new ArrayList<Circle>(); drawall( lc ); $ javac -Xlint:unchecked Shapes.java

40 Bound Wildcards <? extends Shape> can be read as any unknown subclass of Shape It s still an unknown type, so the compiler still prevents its use as a method parameter But the compiler does allow methods of Shape to be called on the unknown subclass There is also <? super Shape> which is any unknown superclass of Shape

41 Generic Methods Classes and interfaces are not the only things that can be parameterized Methods can also be parameterized we ve seen one already: Collections.max() Here s a simplified version of its signature: <T extends Comparable> T max( Collection<T> c ) parameter list (with bound!) return type parameterized argument type

42 Calling Generic Methods There is usually no need to bind the type parameters explicitly the compiler deduces them from context! String s = max( new ArrayList<String>() ); But the parameters can be bound explicitly if necessary: this.<string>max( new ArrayList<String>() ); Foo.<String>staticMax(new ArrayList<String>()); Must have a receiver!

43 Type Variable Scope The scope of a type variable on a class is the instance variables and methods of that class The scope of a type variable on a generic method is the body of that method Static methods can reference their own type variables, but not those of the enclosing class Static fields cannot use type variables

44 Scope Example class Demo<T> { T instv; T method1( T arg ) {} <T> method2( T arg1, T arg2 ) {} static void smethod1( T arg ) {} // no! static <T> int smethod2( T[] arg ) {} // yes! } static T statv; // no! The circled T s have no relationship to each other. In actual code, a different letter should be used for each one

45 Restrictions on Type Variables Cannot be bound to a primitive type Map<int,String> m; // not allowed Cannot be the target of new T create() { return new T(); } // nope Cannot be used to overload methods class MyClass<T,U> { void amethod(t) {...} void amethod(u) {...} }

46 No Generic Exceptions Exceptions cannot be parameterized class PException<T> extends Exception {... Because eventually you d want to } catch( PException<Date> ex ) {......but, generic types only exist at compile type, and thrown exceptions exist only at runtime, so that makes no sense!

47 No Runtime Type Checking Generic types cannot be used with instanceof if( t instanceof FutureTask<List<String>> ) {......because instanceof happens at runtime, but the generic type only exists at compile time Casting to a generic type produces an unchecked warning List<String> ls = (List<String>)foo.getList();...I ll bet you can guess why!

48 Arrays and Generics: Why can t we just get along? You can t create an array of generic types: new Map<String,String>[10]; // won t compile...although oddly you can declare a variable of that type Nor bind an array to a type parameter: Map<String,String[]> mas; // no mas! But you can check an array s compile time type via a type variable: <T> boolean contains( T[] a, T element ) {...

49 Java Generics vs C++ Templates As ever, Java borrowed C++ syntax and made it mean something very different Type erasure vs code generation Bounded type variables vs structural/latent/ duck typing (c2/eckel/thomas) Java generics are not a metaprogramming facility

50 Generic Objections Templates in C++ were too complicated Fair enough, but Java generics are implemented in a very different way, that avoids many of the pitfalls Java generics aren t as powerful as C++ templates Yes. See above...

51 Generic Objections Sun made bad implementation choices It s arguable many of the restrictions on generics are an attempt to preserve binary and source compatibility still, the result is a more expressive language I don t like the compiler doing stuff behind my back I'm sorry have you seen what try/finally or an inner class compiles to? Or even boolean not? Automatic casts are the least of your worries...

52 Resources Sun's Java Generics Tutorial Angelika Langer's Java Generics FAQ Draft Specification Final Specification The Java Language Specification, 3rd edition (not yet published!)

Rules and syntax for inheritance. The boring stuff

Rules 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 information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. 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 information

Advances in Programming Languages: Type accuracy

Advances in Programming Languages: Type accuracy Advances in Programming Languages: Type accuracy Stephen Gilmore The University of Edinburgh January 29, 2007 Introduction Strongly typed programming languages catch programmer errors, leading to program

More information

Java 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 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 information

More than you ever wanted to know about. Java Generics. Jeff Meister CMSC 420 Summer 2007

More than you ever wanted to know about. Java Generics. Jeff Meister CMSC 420 Summer 2007 More than you ever wanted to know about Java Generics Jeff Meister CMSC 420 Summer 2007 The obligatory review of the boring stuff, or GENERICS: A YOUNG LADY S ILLUSTRATED PRIMER IN FOUR SLIDES Java 1.4:

More information

CS61B 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: 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 information

1.1. Annotations History Lesson - C/C++

1.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 information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. 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 information

CS61B 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: 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 information

generic programming alberto ferrari university of parma

generic 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 information

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping

Outline. 1 Generic Classes. 2 Generics and Subtyping. Generics. Guy Wiener. Generic Classes. Generics and Subtyping Outline 1 2 Outline 1 2 (Parametric) classes are classes that have Parameters A generic class with a concrete type parameter is an instance of the generic class The type parameter can be the type of variables,

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 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 information

Pieter van den Hombergh Richard van den Ham. March 1, 2018

Pieter van den Hombergh Richard van den Ham. March 1, 2018 ,, Pieter van den Hombergh Richard van den Ham Fontys Hogeschool voor Techniek en Logistiek Type : Upper March 1, 2018 /FHTenL, March 1, 2018 1/29 Topics, Type : Upper Type : Lower Bounds, accepting things

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 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 information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss 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 information

Java Programming Training for Experienced Programmers (5 Days)

Java 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 information

Java: exceptions and genericity

Java: 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 information

CS61B 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. 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 information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core 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 information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Example List myintlist = new LinkedList(); // 1 myintlist.add(new Integer(0)); // 2 Integer x = (Integer) myintlist.iterator().next(); // 3

More information

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

Announcements. 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 information

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

CSE 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 information

Generics method and class definitions which involve type parameters.

Generics method and class definitions which involve type parameters. Contents Topic 07 - Generic Programming I. Introduction Example 1 User defined Generic Method: printtwice(t x) Example 2 User defined Generic Class: Pair Example 3 using java.util.arraylist II. Type

More information

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

09/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 information

Java 5 New Language Features

Java 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 information

JAVA An overview for C++ programmers

JAVA An overview for C++ programmers JAVA An overview for C++ programmers Wagner Truppel wagner@cs.ucr.edu edu March 1st, 2004 The early history James Gosling, Sun Microsystems Not the usual start for a prog.. language Consumer electronics,

More information

The collections interfaces

The collections interfaces Generics in Java Advanced Programming 4/18/16 1 The collections interfaces Contains unique elements Maps unique keys to values 4/18/16 2 Collections in Java Array has a special language support Iterators

More information

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Example List myintlist = new LinkedList(); // 1 myintlist.add(new Integer(0)); // 2 Integer x = myintlist.iterator().next(); // 3 3 Example

More information

CS108, Stanford Handout #8. Java Generics

CS108, 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 information

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø

More information

What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods

What 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 information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS61B 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 information

EMBEDDED SYSTEMS PROGRAMMING More About Languages

EMBEDDED SYSTEMS PROGRAMMING More About Languages EMBEDDED SYSTEMS PROGRAMMING 2015-16 More About Languages JAVA: ANNOTATIONS (1/2) Structured comments to source code (=metadata). They provide data about the code, but they are not part of the code itself

More information

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com

JDK 7 (2011.7) knight76.tistory.com Knight76 at gmail.com JDK 7 (2011.7) JDK 7 #2 Project Coin knight76.tistory.com Knight76 at gmail.com 1 Project Coin 2 Project Leader Joseph D. Darcy( ) IDEA 2 27, 2009 3 30, 2009 (open call) 70 jdk 7, Language, The Java programming-language

More information

CS11 Java. Fall Lecture 1

CS11 Java. Fall Lecture 1 CS11 Java Fall 2006-2007 Lecture 1 Welcome! 8 Lectures Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7-8 Lab Assignments Made available on Mondays Due one week later Monday, 12 noon

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP 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 information

CSC 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 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 information

JVML Instruction Set. How to get more than 256 local variables! Method Calls. Example. Method Calls

JVML Instruction Set. How to get more than 256 local variables! Method Calls. Example. Method Calls CS6: Program and Data Representation University of Virginia Computer Science Spring 006 David Evans Lecture 8: Code Safety and Virtual Machines (Duke suicide picture by Gary McGraw) pushing constants JVML

More information

PIC 20A Collections and Data Structures

PIC 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 information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. 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 information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

The Java Programming Language

The Java Programming Language The Java Programming Language Slide by John Mitchell (http://www.stanford.edu/class/cs242/slides/) Outline Language Overview History and design goals Classes and Inheritance Object features Encapsulation

More information

CSE 331. Generics (Parametric Polymorphism)

CSE 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

interface MyAnno interface str( ) val( )

interface MyAnno interface str( ) val( ) Unit 4 Annotations: basics of annotation-the Annotated element Interface. Using Default Values, Marker Annotations. Single-Member Annotations. The Built-In Annotations-Some Restrictions. 1 annotation Since

More information

Semantic Analysis. Lecture 9. February 7, 2018

Semantic Analysis. Lecture 9. February 7, 2018 Semantic Analysis Lecture 9 February 7, 2018 Midterm 1 Compiler Stages 12 / 14 COOL Programming 10 / 12 Regular Languages 26 / 30 Context-free Languages 17 / 21 Parsing 20 / 23 Extra Credit 4 / 6 Average

More information

CS 251 Intermediate Programming Inheritance

CS 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 information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1 CSE P 501 Compilers Java Implementation JVMs, JITs &c Hal Perkins Winter 2008 3/11/2008 2002-08 Hal Perkins & UW CSE V-1 Agenda Java virtual machine architecture.class files Class loading Execution engines

More information

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed. Enums Introduction In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed. The Final Tag To display why this is useful, I m going to

More information

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes

Problems. 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 information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Comp215: Thinking Generically

Comp215: Thinking Generically Comp215: Thinking Generically Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. Functional APIs On Wednesday, we built a list of Objects. This works. But it sucks. class

More information

Exceptions. When do we need exception mechanism? When and why use exceptions? The purpose of exceptions

Exceptions. When do we need exception mechanism? When and why use exceptions? The purpose of exceptions Exceptions When do we need exception mechanism? When and why use exceptions? The purpose of exceptions Exceptions An exception is thrown when there is no reasonable way for the code that discovered the

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

CS 211: Using ArrayList, Implementing Arraylist

CS 211: Using ArrayList, Implementing Arraylist CS 211: Using ArrayList, Implementing Arraylist Chris Kauffman Week 12-1 Collections Java has a nice library of containers, Collections framework Interfaces that provide get, set, add methds, conversion

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

JAVA V Assertions Java, winter semester

JAVA 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 information

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet. Mr G s Java Jive #2: Yo! Our First Program With this handout you ll write your first program, which we ll call Yo. Programs, Classes, and Objects, Oh My! People regularly refer to Java as a language that

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Parametric polymorphism and Generics

Parametric 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 information

JAVA V Source files Java, winter semester

JAVA V Source files Java, winter semester JAVA Source files 17.10.2017 1 Unicode programs ~ Unicode comments, identifiers, char and string constants the rest is in ASCII (

More information

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here.

CS61B Lecture #12. Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here. CS61B Lecture #12 Programming Contest: Coming up Saturday 5 October. See the contest announcement page, here. Lateness: Yes, the lateness policy does extend to Project 0. Test 1: still scheduled for 16

More information

Comp 249 Programming Methodology Chapter 9 Exception Handling

Comp 249 Programming Methodology Chapter 9 Exception Handling Comp 249 Programming Methodology Chapter 9 Exception Handling Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted,

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

Selected Java Topics

Selected 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 information

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal Version date:

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal  Version date: Java Brand Generics Advanced Topics in Java Khalid Azim Mughal khalid@ii.uib.no http://www.ii.uib.no/~khalid/atij/ Version date: 2005-03-03 Khalid Azim Mughal Java Brand Generics 1/40 Overview Introduction

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information

104. Intermediate Java Programming

104. Intermediate Java Programming 104. Intermediate Java Programming Version 6.0 This course teaches programming in the Java language -- i.e. the Java Standard Edition platform. It is intended for students with previous Java experience

More information

ArrayList. Introduction. java.util.arraylist

ArrayList. Introduction. java.util.arraylist ArrayList Introduction In this article from my free Java 8 course, I will be giving you a basic overview of the Java class java.util.arraylist. I will first explain the meaning of size and capacity of

More information

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Lecture 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 information

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++

Crash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++ Crash Course in Java Netprog: Java Intro 1 Why Java? Network Programming in Java is very different than in C/C++ much more language support error handling no pointers! (garbage collection) Threads are

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Introduction to Programming Using Java (98-388)

Introduction 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 information

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java

More information

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

11/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 information

CS 11 java track: lecture 3

CS 11 java track: lecture 3 CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces

More information

Advances in Programming Languages: Generics, interoperability and implementation

Advances in Programming Languages: Generics, interoperability and implementation Advances in Programming Languages: Generics, interoperability and implementation Stephen Gilmore The University of Edinburgh February 1, 2007 Understanding generic code Generic Java extends Java with generic

More information

CS 211: Using ArrayList, Implementing Arraylist

CS 211: Using ArrayList, Implementing Arraylist CS 211: Using ArrayList, Implementing Arraylist Chris Kauffman Week 12-1 Front Matter Goals Today ArrayList Use ArrayList Implementation Reading Lab Manual Ch 17: Generics BJP Ch 10.1: Using ArrayList

More information

Generics 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 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 information

20 Subclassing and Mutation

20 Subclassing and Mutation Object-Oriented Design Lecture 20 CS 3500 Spring 2010 (Pucella) Tuesday, Mar 30, 2010 20 Subclassing and Mutation Suppose we have a class A that subclasses a class B (which I will write A B). Should we

More information

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation

Object-Oriented Software Engineering. Chapter 2: Review of Object Orientation Object-Oriented Software Engineering Chapter 2: Review of Object Orientation 2.1 What is Object Orientation? Procedural paradigm: Software is organized around the notion of procedures Procedural abstraction

More information

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007 Advanced Topics in Java and on Security in Systems Effective Generics Eirik Eltvik 26 th of February 2007 Taking care when calling Legacy code Checks at compile-time is not always appropriate When? Legacy

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes. a and Interfaces Class Shape Hierarchy Consider the following class hierarchy Shape Circle Square Problem AND Requirements Suppose that in order to exploit polymorphism, we specify that 2-D objects must

More information

Test Class A. public class A { private int x, y; public int getx() { return x; } public int gety() { return y; }

Test Class A. public class A { private int x, y; public int getx() { return x; } public int gety() { return y; } Test Class A Two simple exampel classes public class A { private int x, y; public int getx() { return x; public int gety() { return y; public A( int ax, int ay ) { x = ax; y = ay; public String tostring()

More information

+ Abstract Data Types

+ 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 information

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

CS2110 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 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 information

Homework #10 due Monday, April 16, 10:00 PM

Homework #10 due Monday, April 16, 10:00 PM Homework #10 due Monday, April 16, 10:00 PM In this assignment, you will re-implement Dictionary as Map container class using the same data structure. A Map has an associated entry set and that set will

More information

Implements vs. Extends When Defining a Class

Implements vs. Extends When Defining a Class Implements vs. Extends When Defining a Class implements: Keyword followed by the name of an INTERFACE Interfaces only have method PROTOTYPES You CANNOT create on object of an interface type extends: Keyword

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Photo credit: Andrew Kennedy JAVA GENERICS

Photo 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 information

CSE 341, Autumn 2015, Ruby Introduction Summary

CSE 341, Autumn 2015, Ruby Introduction Summary CSE 341, Autumn 2015, Ruby Introduction Summary Disclaimer: This lecture summary is not necessarily a complete substitute for atting class, reading the associated code, etc. It is designed to be a useful

More information

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

More information

Primitive Java Generic Class

Primitive Java Generic Class Primitive Java Generic Class 1 A buffer pool is a data structure that caches records retrieved from a disk file, in order to improve an application's performance. Typically, the pool stores some sort of

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html

More information