12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.

Slides:



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

Introduction to Arrays Chapter What is an array? An array is an ordered collection that stores many elements of the same type within one variable.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
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.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
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 McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java Generics.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
(c) University of Washington14-1 CSC 143 Java Collections.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
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.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
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.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
12-CRS-0106 REVISED 8 FEB 2013 Java Collection. 12-CRS-0106 REVISED 8 FEB 2013 Java Collection.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
ADSA: Generics/ Advanced Data Structures and Algorithms Objective –to describe basic forms of generic classes, interfaces, and methods for searching.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Introduction to Generics
CSE 143 Lecture 2 ArrayList reading: 10.1 slides created by Marty Stepp
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
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:
List Interface and Linked List Mrs. Furman March 25, 2010.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
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.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Interfaces. In order to work with a class, you need to understand the public methods  methods, return types,…  after you instantiate, what can you do.
Collections Dwight Deugo Nesa Matic
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.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
CSC 520 – Advanced Object Oriented Programming, Fall, 2010 Thursday, September 30 Week 5, Generics and Inheritance Techniques, Meyer Ch. 10 & 16.
ADT’s, Collections/Generics and Iterators
Chapter 20 Generic Classes and Methods
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Generic programming in Java
Object Oriented Programming in java
Java Programming Language
Review: libraries and packages
Iterators Dan Fleck.
Review for Midterm 3.
Presentation transcript:

12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming

12-CRS-0106 REVISED 8 FEB 2013 A way to define which types are allowed in your class or function Generic types are declared in class and defined while instantiation Generic Type

12-CRS-0106 REVISED 8 FEB 2013 the compiler will replace all occurrences in the class of type parameter with the upper bound of the formal type parameter The default upper bound is the class Object Erasure

12-CRS-0106 REVISED 8 FEB 2013 Picture it that we want to create a class to store anything within Let the class called SafeBox Example

12-CRS-0106 REVISED 8 FEB 2013 Example SafeBox{goods=10} SafeBox{goods=Some Text}

12-CRS-0106 REVISED 8 FEB 2013 Now, let’s say that we want to create (instantiate) a SafeBox object that can only contain a specific type of value Here, we can use Generic Example

12-CRS-0106 REVISED 8 FEB 2013 Declare Generic type name after class name, enclosed with <> –public class SafeBox {... Use Generic type name to declare generic variables –private X genericVar; Define the Generic type when instantiation –SafeBox sb1 = new SafeBox(); –SafeBox sb2 = new SafeBox(); Example

12-CRS-0106 REVISED 8 FEB 2013 Example SafeBox{goods=10} SafeBox{goods=Some Text} When the SafeBox is instantiate without generic, the default type for is Object

12-CRS-0106 REVISED 8 FEB 2013 Example Specify the generic type during instantiation The defined type will “replace” the generic type This line is error compile as now goods can only be assigned with String

12-CRS-0106 REVISED 8 FEB 2013 Suppose we want to use an Object with Generic properties as a parameter of a method There are 3 ways of using : –Default use –Bounded use –Unbounded use Wildcard

12-CRS-0106 REVISED 8 FEB 2013 Default use (no Wildcard) With no wildcard, the method will receive any SafeBox object and treat the Generic type as default Object type safe box = SafeBox{goods=Hallo} safe box = SafeBox{goods=text 2} safe box = SafeBox{goods=10}

12-CRS-0106 REVISED 8 FEB 2013 The use of Bounded Wildcard is when we specified a specific type of Generic that can be received by the method Declare the specified Generic type of a parameter enclosed in <> –public void methodName( SomeObject ) Bounded Wildcard

12-CRS-0106 REVISED 8 FEB 2013 Bounded Wildcard This line is error compile as now doSomething can receive Default SafeBox and Integer SafeBox only

12-CRS-0106 REVISED 8 FEB 2013 Using unbounded wildcard will make the method can receive any Generic type Object Declare Unbounded Wildcard using –public void methodName( SomeObject ) Unbounded Wildcard

12-CRS-0106 REVISED 8 FEB 2013 The notation means that we don’t know the specific type –In another word, we ignore the type But not like default use, the use of unbounded wildcard will make the generic value from the Object cannot be modified inside the method –Because we don’t know the type –No modification, only accessed –Non generic variable can still be modified Unbounded Wildcard

12-CRS-0106 REVISED 8 FEB 2013 Unbounded Wildcard This line is error compile as the type of goods is unknown, thus cannot be modified Can still be accessed

12-CRS-0106 REVISED 8 FEB 2013 Since using no wildcard (RAW type) will treat the generic as Object-type, any modification might cause exceptions –Because raw type has no restrictions, using it will easily corrupt the invariant of collection. –In brief, wildcard type is safe and the raw type is not. –We can not put any element into a Set No Wildcard vs Unbounded Wildcard

12-CRS-0106 REVISED 8 FEB 2013 Bounded Wildcard safe box = SafeBox{goods=10}

12-CRS-0106 REVISED 8 FEB 2013 Bounded Wildcard This line will caused an exception as the value of goods is Integer, and want to be retrieved as String No error compile as goods in sb2 IS declared as String

12-CRS-0106 REVISED 8 FEB 2013 Java Collection

12-CRS-0106 REVISED 8 FEB 2013 Java Collection containers of Objects which by polymorphism can hold any class that derives from Object (which is actually, any class) Using Generics the Collection classes can be aware of the types they store

12-CRS-0106 REVISED 8 FEB 2013 Java Collection add( item ) remove( item ) addAll( collection ) removeAll( collection ) retainAll( collection ) contains( item )

12-CRS-0106 REVISED 8 FEB 2013 Java Collection List list = new ArrayList(); // normal loop for (int i = 0; i < list.size() ; i++ ) { Object o = list.get(i); System.out.println(o); } // loop using for-element for (Object o : list) { System.out.println(o); }

12-CRS-0106 REVISED 8 FEB 2013 Java Collection // Loop using iterator Iterator itr = list.iterator(); while (itr.hasNext()) { Object o = itr.next(); System.out.println(o); } // loop using lambda Expression list.forEach( o -> System.out.println(o)); // loop using reference list.forEach( System.out :: println);

12-CRS-0106 REVISED 8 FEB 2013 Generic Collection Collection str = new HashSet (); List arr_i = new List (); ArrayList emp = new ArrayList ();

12-CRS-0106 REVISED 8 FEB 2013 Sorting Collection – Comparable Collections.sort( list ) or list.sort( null ) –If the List consists of String elements, it will be sorted into alphabetical order. –If it consists of Date elements, it will be sorted into chronological order –To create a custom ordering for list of objects, the class must implement interface Comparable  implement method public int compareTo( Object ) For arrays, use Arrays.sort( array[] )

12-CRS-0106 REVISED 8 FEB 2013 Sorting Collection – Comparable public int compareTo( Object o ) –Return < 0 if “this” object will be sorted before Object o –Return = 0 if “this” object and Object o is equal –Return > 0 if “this” object will be sorted after Object o If the parameter is either String or Date, use compareTo –return this.getString().compareTo(o.getString()); If the parameter is numerical, use substraction –return this.getNumber() – o.getNumber();

12-CRS-0106 REVISED 8 FEB 2013 Example - sort(list of string)

12-CRS-0106 REVISED 8 FEB 2013 Example – sort(list of object)

12-CRS-0106 REVISED 8 FEB 2013 Example – sort(list of object) name=anna, salary=15.0 name=bobby, salary=5.0 name=erick, salary=56.0 name=rey, salary=25.0

12-CRS-0106 REVISED 8 FEB 2013 Sorting Collection - Comparator Comparable Interface only allows to sort a single property. To sort with multiple properties, you need Comparator class Collections.sort( list, comparator ) or list.sort( comparator ) For arrays, use Arrays.sort( array[], comparator )

12-CRS-0106 REVISED 8 FEB 2013 Sorting Collection - Comparator Create a comparator class implements Comparator interface to compare the element –public interface Comparator { int compare(T object1, T object2); }

12-CRS-0106 REVISED 8 FEB 2013 Sorting Collection Example name=anna, salary=15.0 name=bobby, salary=5.0 name=erick, salary=56.0 name=rey, salary=25.0 name=bobby, salary=5.0 name=anna, salary=15.0 name=rey, salary=25.0 name=erick, salary=56.0

12-CRS-0106 REVISED 8 FEB 2013 Filter elements from Collections Select a specific element based on parameter –Select all Employee with salary above 20 Old way

12-CRS-0106 REVISED 8 FEB 2013 Filter elements from Collections Select all Employee with salary above 20 Using Lambda expression –list.stream().filter( o -> condition )

12-CRS-0106 REVISED 8 FEB 2013 Filter elements from Collections Retrieve an element based on some attributes –Select Employee by name Old way

12-CRS-0106 REVISED 8 FEB 2013 Filter elements from Collections Select Employee by name Using Lambda expression –list.stream().filter( o -> condition ).findFirst() –.orElse( x )

12-CRS-0106 REVISED 8 FEB 2013 Question?

12-CRS-0106 REVISED 8 FEB 2013 THANK YOU Credits M usic : Yonezawa Madoka - Oui! Ai Kotoba (Instrumental)