30-Jun-15 Generics. Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom",

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 21 Generics.
Java Generics.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
1 Generics, Type Safety, and Dynamic Data Structures.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Generics OOP Tirgul What is it good for ? Stack myStack = new Stack() ; // old version (1.4.2) myStack.push(new Integer(0)) ; int x = ((Integer)
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Generics and Type Safety Recitation – 4/24/2009 CS 180 Department of Computer Science, Purdue University.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Chapter 19 Java Data Structures
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java Generics.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Effective Java: Generics Last Updated: Spring 2009.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
ArrayList, Multidimensional Arrays
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Chapter 18 Java Collections Framework
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
Types in programming languages1 What are types, and why do we need them?
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Java 1.5 Generics Amr Ali Software Engineer, IBM-Egypt EG-JUG.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
CS202 Java Object Oriented Programming Introduction to Collection Classes Chengyu Sun California State University, Los Angeles.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 19 Java Data Structures
Generics A Brief Review 16-Nov-18.
Generics 27-Nov-18.
Review: libraries and packages
Generics 2-May-19.
Presentation transcript:

30-Jun-15 Generics

Arrays and collections In Java, array elements must all be of the same type: int[] counts = new int[10]; String[] names = { "Tom", "Dick", "Harry" }; Hence, arrays are type safe: The compiler will not let you put the wrong kind of thing into an array A collection, such as a Vector or ArrayList, cannot hold primitives, but will accept any type of Object : Stack someStuff = new Stack(); someStuff.push("A String is an Object"); someStuff.push(Color.BLUE); We can make an array that, like a collection, holds any Objects: Object[ ] whatever = new Object[100]; Prior to Java 5, there was no easy way to make a collection type safe

Making a collection type safe Here’s how to create a type-safe Stack that holds only Strings (in Java 1.4 and earlier): class StackOfStrings { private Stack internalStack = new Stack(); public boolean isEmpty() { return internalStack.isEmpty(); } public String push(String s) { internalStack.push(s); return s; } public String pop() { return (String)internalStack.pop(); } etc.

Generics for type safety in Java 5 In Java 5, you can easily make any collection type safe For example, you can create a Stack that holds only Strings as follows: Stack names = new Stack (); You can write methods that require a type-safe collection as follows: void printNames(Stack names) { String nextName = names.pop(); // no casting needed! names.push("Hello"); // works just the same as before names.push(Color.RED); // compile-time error!

What generics are and aren’t You can almost think of generics as defining new types--for example a Stack is a stack of strings In Java 1.4, String s = myStack.pop(); will not compile String s = (String)myStack.pop(); compiles, with runtime check myStack.push(Color.RED); compiles with no complaint In Java 5, String s = myStack.pop(); Compiles with no runtime check if myStack was declared as Stack Does not compile if myStack was declared any other way myStack.push(Color.RED); is a compiler error (= syntax error) However, generics are instructions to the compiler only You can still say: if (thing instanceof Stack)... but you cannot say: if (thing instanceof Stack )... This is called erasure--the type information is “erased” at runtime

Generics in CIT594 Generics are important in studying data structures because: We make heavy use of Sun’s collections, all of which have been genericized, so we need to know how to use them However, non-genericized collections continue to work Genericized collections include: LinkedList, ArrayList, Vector, HashSet, TreeSet, Stack, HashMap, TreeMap, PriorityQueue, and others When we create new data structures, In Java 5, it is almost always a good idea to genericize them However, Java 5 programs will only work for users who have upgraded their Java systems--so we may wish to compile for older versions Generics are not important in data structures because: Generics are only a convenient way to get type safety The data structures themselves have not changed in any way

Using an existing collection Creation: Stack plainStack = new Stack(); // the old way Stack s1 = new Stack (); // s1 is still just a plain stack Stack integerStack = new Stack (); // correct Stack s2 = new Stack(); // works with a warning Assignments: plainStack = integerStack; // no problem with this integerStack = plainStack; // works but is not type safe Use of integerStack : integerStack.push(new Integer(5)); Integer xxx = integerStack.pop(); // no cast necessary integerStack.push(5); // works, because of autoboxing int x =integerStack.pop(); // works, because of auto unboxing

Methods with generics private static void fiddle(Stack ints) { ints.push(5); } fiddle(integerStack); // good call fiddle(plainStack); // legal but not type safe fiddle(new Stack ()); // not legal static Stack myMethod(Stack stk) { Stack result = new Stack (); return result; } Stack newStack = myMethod(integerStack); // good call Stack newStack1 = myMethod(plainStack); // not safe

Bad news Type safe? Only sort of... Stack stack1 = new Stack (); Stack stack2 = stack1; // stack2 is alias of stack1 stack2.push(Color.RED);// legal--stack2 is a plain stack Integer xxx = stack1.pop(); // ClassCastException! A little more explanation... Java 5 is upwardly compatible with Java 1.4--that is, old programs must continue to work Hence you can have non-generic stacks (and stack assignment) When you use a generic collection, you should make it generic everywhere, not just in the places that Java would otherwise report an error Eclipse will provide warnings for many unsafe cases, so pay close attention to those warnings!

Writing your own generic classes  public class MyClass { T value; // in this class, use T just like any other type  public MyClass(T value) this.value = value; }  public void print(T anotherValue) { System.out.println(value + " " + anotherValue); } }}

Iterators An iterator gives you every element of a collection, one at a time The collection has a type iterator(); factory method to return a new iterator to return objects of the given type The method boolean hasNext() tells you if there are more objects The method type next() returns the next object The method void remove() deletes the last object gotten Example: Iterator iter = integerStack.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); }

The “enhanced for loop” Java 5’s new for loop does the iterator work for you for (int n : integerStack) { System.out.println(n); } is the same (except for the int declaration) as Iterator iter = integerStack.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } The enhanced for loop can also be used for arrays, and for any class you write that implements the Iterator interface The enhanced for loop is convenient but less powerful than the old-style for loop, since it just goes through every element in a forward direction only

Subclassing a generic class  import java.awt.Color; public class Subclass extends MyClass {  // You almost always need to supply a constructor public Subclass(Color color) { super(color); }  public static void main(String[ ] args) { Subclass sc = new Subclass(Color.GREEN); sc.print(Color.WHITE); } }}

Summary It looks as if generics save you from having to do casting, at the expense of more work in the declarations The real benefit is that they replace run-time checks (and run-time errors) with compile-time checks (and syntax errors) This makes your program both more reliable and easier to debug

The End