Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.

Slides:



Advertisements
Similar presentations
Java Programming: Guided Learning with Early Objects
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Generics, Lists, Interfaces
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Generics and the ArrayList Class
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Generic programming in Java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
 2006 Pearson Education, Inc. All rights reserved Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
1 L42 Collections (2). 2 OBJECTIVES  To use collections framework algorithms to manipulate  search  sort  and fill collections.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
 2006 Pearson Education, Inc. All rights reserved Generics.
Chapter 19 Java Data Structures
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 22 Lists, Stacks, Queues, and Priority.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Data Structures Using C++ 2E
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
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.
INHERITANCE, POLYMORPHISM, CLASS HIERARCHIES AND GENERICS.
CISC6795, Spring 2011 Dr. Zhang Generics & Collections.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
 2005 Pearson Education, Inc. All rights reserved Generics.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
 Pearson Education, Inc. All rights reserved Collections.
Chapter 18 Java Collections Framework
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Understanding Data Types and Collections Lesson 2.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templates.
C++ How to Program, 9/e © by Pearson Education, Inc. All Rights Reserved.
CIS 270—Application Development II Chapter 18-Generics.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
©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.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSCI-383 Object-Oriented Programming & Design Lecture 25.
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.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Chapter 18 Introduction to Custom Templates C++ How to Program, 9/e ©2016 by Pearson Education, Inc., Hoboken, NJ. All Rights Reserved. Instructor Note:
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.
 Pearson Education, Inc. All rights reserved. 1 Ch 18 Generics OBJECTIVES In this chapter you will learn:  To create generic methods that perform.
Lecture 10 Collections Richard Gesick.
Chapter 20 Generic Classes and Methods
ARRAYLIST AND VECTOR.
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.
CS313D: Advanced Programming Language
Chapter 9 Inheritance and Polymorphism
Object Oriented Programming in java
Fundaments of Game Design
Generic Classes and Methods
Presentation transcript:

Generics and Collections

Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods A single method declaration A set of related methods Generic classes A single class declaration A set of related clases

Motivation for Generic Methods Overloaded methods Perform similar operations on different types of data Overloaded printArray methods Integer array Double array Character array Only reference types can be used with generic methods and classes

Motivation for Generic Methods (Cont.) Study each printArray method Array element type appears in two location Method header for statement Combine three printArray methods into one Replace the element types with a generic name E Declare one printArray method Display the string representation of the elements of any array

Generic Methods: Implementation and Compile-Time Translation Generic method declaration Type parameter section Delimited by angle brackets ( ) Precede the method’s return type Contain one or more type parameters Also called formal type paramters

Generic Methods: Implementation and Compile-Time Translation Type parameter (Also known as type variable) An identifier that specifies a generic type name Used to declare return type, parameter types and local variable types Act as placeholders for the types of the argument passed to the generic method Actual type arguments Can be declared only once but can appear more than once public static void printTwoArrays( E[] array1, E[] array2 )

Generic Methods: Implementation and Compile-Time Translation (Cont.) Compile-time translation Erasure Remove type parameter section Replace type parameters with actual types Default type is Object

Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type Application of Fig Generic method Use Type parameters in the return type and parameter list Generic interface Specify, with a single interface declaration, a set of related types E.g., Comparable Method integer1.compareTo( integer2 ) Compare two objects of the same class Return 0 if two objects are equal Return -1 if integer1 is less than integer2 Return 1 if integer1 is greater than integer2

Additional Compile-Time Translation Issues: Methods That Use a Type Parameter as the Return Type (Cont.) Upper bound of type parameter Default is Object Always use keyword extends E.g., T extends Comparable When compiler translates generic method to Java bytecode Replaces type parameter with its upper bound Insert explicit cast operation e.g., line 23 of Fig I preceded by an Integer cast (Integer) maximum( 3, 4, 5 )

Overloading Generic Method Generic method may be overloaded By another generic method Same method name but different method parameters By non-generic methods Same method name and number of parameters When compiler encounters a method call Search for most precise matching method first Exact method name and argument types Then search for inexact but applicable matching method

Generic Classes Generic classes Use a simple, concise notation to indicate the actual type(s) At compilation time, Java compiler ensures the type safety uses the erasure technique to enable client code to interact with the generic class Parameterized classes Also called parameterized types E.g., Stack

Generic Classes (Cont.) Generic class declaration Looks like a non-generic class declaration Except class name is followed by a type parameter section The –Xlint:unchecked option Compiler cannot 100% ensure type safety

Generic Classes (Cont.) Generic class at compilation time Compiler performs erasure on class’s type parameters Compiler replaces type parameters with their upper bound Generic class test program at compilation time Compiler performs type checking Compiler inserts cast operations as necessary

Generic Classes (Cont.) Creating generic methods to test class Stack Method testPush Perform same tasks as testPushDouble and testPushInteger Method testPop Perform same tasks as testPopDouble and testPopInteger

Wildcards in Methods That Accept Type Parameters Data structure ArrayList Dynamically resizable, array-like data structure Method add Method toString

Wildcards in Methods That Accept Type Parameters Motivation for using wildcards Implement a generic method sum Total the numbers in a collection Receive a parameter of type ArrayList Use method doubleValue of class Number to obtain the Number ’s underlying primitive value as a double value

Wildcards in Methods That Accept Type Parameters (Cont.) Implementing method sum with a wildcard type argument in its parameter Number is the superclass of Integer ArrayList is not a supertype of ArrayList Cannot pass ArrayList to method sum

Generics and Inheritance: Notes Inheritance in generics Generic class can be derived from non-generic class e.g., class Object is superclass of every generic class Generic class can be derived from another generic class e.g., Stack is a subclass of Vector Non-generic class can be derived from generic class e.g., Properties is a subclass of Hashtable Generic method in subclass can override generic method in superclass If both methods have the same signature

Collections

Introduction Java collections framework Contain prepackaged data structures, interfaces, algorithms Use generics Use existing data structures Example of code reuse Provides reusable components

Collections Overview Collection Data structure (object) that can hold references to other objects Collections framework Interfaces declare operations for various collection types Provide high-performance, high-quality implementations of common data structures Enable software reuse

Some collection framework interfaces.

Class Arrays Provides static methods for manipulating arrays Provides “high-level” methods Method binarySearch for searching sorted arrays Method equals for comparing arrays Method fill for placing values into arrays Method sort for sorting arrays

Interface Collection and Class Collections Interface Collection Root interface in the collection hierarchy Interfaces Set, Queue, List extend interface Collection Set – collection does not contain duplicates Queue – collection represents a waiting line List – ordered collection can contain duplicate elements Contains bulk operations Adding, clearing, comparing and retaining objects Provide method to return an Iterator object Walk through collection and remove elements from collection

Interface Collection and Class Collections (Cont.) Class Collections Provides static methods that manipulate collections Implement algorithms for searching, sorting and so on Collections can be manipulated polymorphically Synchronized collection Unmodifiable collection

Software Engineering Observation The collections framework algorithms are polymorphic. That is, each algorithm can operate on objects that implement specific interfaces, regardless of the underlying implementations.

Lists List Ordered Collection that can contain duplicate elements Sometimes called a sequence Implemented via interface List ArrayList LinkedList Vector

Performance Tip ArrayLists behave like Vectors without synchronization and therefore execute faster than Vectors because ArrayLists do not have the overhead of thread synchronization.

Software Engineering Observation LinkedLists can be used to create stacks, queues, trees and deques (double-ended queues, pronounced “decks”). The collections framework provides implementations of some of these data structures.

ArrayList and Iterator ArrayList example Demonstrate Collection interface capabilities Place two String arrays in ArrayList s Use Iterator to remove elements in ArrayList

LinkedList LinkedList example Add elements of one List to the other Convert String s to uppercase Delete a range of elements

Linkedlist (Cont.) static method asList of class Arrays View an array as a List collection Allow programmer to manipulate the array as if it were a list Any modification made through the List view change the array Any modification made to the array change the List view Only operation permitted on the view returned by asList is set

Vector Class Vector Array-like data structures that can resize themselves dynamically Contains a capacity Grows by capacity increment if it requires additional space

Performance Tip Inserting an element into a Vector whose current size is less than its capacity is a relatively fast operation. Inserting an element into a Vector that needs to grow larger to accommodate the new element is a relatively slow operation.

Collections Algorithms Collections framework provides set of algorithms Implemented as static methods List algorithms sort binarySearch reverse shuffle fill copy

Collections Algorithms Collection algorithms min max addAll frequency disjoint

Collections algorithms.

Algorithm sort sort Sorts List elements Order is determined by natural order of elements’ type List elements must implement the Comparable interface Or, pass a Comparator to method sort Sorting in ascending order Collections method sort Sorting in descending order Collections static method reverseOrder Sorting with a Comparator Create a custom Comparator class

Algorithm binarySearch binarySearch Locates object in List Returns index of object in List if object exists Returns negative value if Object does not exist Calculate insertion point Make the insertion point sign negative Subtract 1 from insertion point