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.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
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.
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.
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.
Java Generics.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
Compilation 2007 Java 1.5 Features Michael I. Schwartzbach BRICS, University of Aarhus.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
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",
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
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.
16-Jul-15 Java Versions of Java Java 1 Java 2 Java 5.0 Oak: Designed for embedded devices Java 1.1: Adds inner classes and a completely new event-handling.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
16 - Generics. 2 NOEA2009Java-kursus – Generics ”Generic” Programming in C#/Java (as it was until Summer 2005) All classes inherit from Object So we can.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
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.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Object Oriented Programming Ders 10: Data Structures Mustafa Emre İlal
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Data structures and algorithms in the collection framework 1.
Holding Your Objects Generics and type-safe containers One of the problems of using pre-Java SE5 containers was that the compiler allowed.
CHAPTER 5 ArrayLists.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Generics CompSci 230 S Software Construction.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Today’s Agenda  Generic  Iterators CS2336: Computer Science II.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CMSC 330: Organization of Programming Languages Java Generics.
GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 15 CS2110 – Fall 2013.
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.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
11-Jan-16 Bits and Pieces Some random things in Java.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
1.Net programmingGenericsNOEA / 2009 Generics 11. Generics in.NET and C#
Generics Starring: Rite-Aid Aspirin Co-Starring: CVS Paper Plates.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
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.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
EKT472: Object Oriented Programming
Java 1.5 New Features 22-Apr-18.
Sixth Lecture ArrayList Abstract Class and Interface
University of Central Florida COP 3330 Object Oriented Programming
Generics A Brief Review 16-Nov-18.
Introduction to Collections
Some random things in Java
Introduction to Collections
Generics 27-Nov-18.
ArrayLists 22-Feb-19.
ArrayLists 27-Apr-19.
Java 5 New Features 1-May-19.
Generics 2-May-19.
COMP204 Bernhard Pfahringer (with input from Robi Malik)
Presentation transcript:

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 ArrayList(); You'll have to say: List words = new ArrayList (); The good news: Replaces runtime type checks with compile-time checks No casting; instead of String title = (String) words.get(i); you use String title = words.get(i); Some classes and interfaces that have been “genericized” are: Vector, ArrayList, LinkedList, Hashtable, HashMap, Stack, Queue, PriorityQueue, Dictionary, TreeMap and TreeSet

Generic Iterators To iterate over generic collections, it’s a good idea to use a generic iterator List listOfStrings = new LinkedList ();... for (Iterator i = listOfStrings.iterator(); i.hasNext(); ) { String s = i.next(); System.out.println(s); } Better yet, use the new for statement (to be discussed)

Writing generic methods private void printListOfStrings(List list) { for (Iterator i = list.iterator(); i.hasNext(); ) { System.out.println(i.next()); } } This method should be called with a parameter of type List, but it can be called with a parameter of type List The disadvantage is that the compiler won’t catch errors; instead, errors will cause a ClassCastException This is necessary for backward compatibility Similarly, the Iterator need not be an Iterator

Type wildcards Here’s a simple (no generics) method to print out any list: private void printList(List list) { for (Iterator i = list.iterator(); i.hasNext(); ) { System.out.println(i.next()); } } The above still works in Java 1.5, but now it generates warning messages Java 1.5 incorporates lint (like C lint ) to look for possible problems You should eliminate all errors and warnings in your final code, so you need to tell Java that any type is acceptable: private void printListOfStrings(List list) { for (Iterator i = list.iterator(); i.hasNext(); ) { System.out.println(i.next()); } }

Writing your own generic types public class Box { private List contents; public Box() { contents = new ArrayList (); } public void add(T thing) { contents.add(thing); } public T grab() { if (contents.size() > 0) return contents.remove(0); else return null; } Sun’s recommendation is to use single capital letters (such as T ) for types Many people, including myself, don’t think much of this recommendation

New for statement The syntax of the new statement is for( type var : array) {...} or for( type var : collection ) {...} Example: for(float x : myRealArray) { myRealSum += x; } For a collection class that has an Iterator, instead of for (Iterator iter = c.iterator(); iter.hasNext(); ) ((TimerTask) iter.next()).cancel(); you can now say for (TimerTask task : c) task.cancel();

New for statement with arrays The new for statement can also be used with arrays Instead of for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } you can say (assuming array is an int array): for (int value : array) { System.out.println(value); } Disadvantage: You don’t know the index of any of your values

Creating a ArrayList the old way The syntax for creating ArrayList s has changed between Java 1.4 and Java 5 For compatibility reasons, the old way still works, but will give you warning messages Here are the (old) constructors: import java.util.ArrayList; ArrayList vec1 = new ArrayList(); Constructs an ArrayList with an initial capacity of 10 ArrayList vec2 = new ArrayList( initialCapacity );

Creating a ArrayList the new way Specify, in angle brackets after the name, the type of object that the class will hold Examples: ArrayList vec1 = new ArrayList (); ArrayList vec2 = new ArrayList (10); To get the old behavior, but without the warning messages, use the wildcard Example: ArrayList vec1 = new ArrayList ();

Accessing with and without generics Object get(int index ) Returns the component at position index Using get the old way: ArrayList myList = new ArrayList(); myList.add("Some string"); String s = (String)myList.get(0); Using get the new way: ArrayList myList = new ArrayList (); myList.add("Some string"); String s = myList.get(0); Notice that casting is no longer necessary when we retrieve an element from a “genericized” ArrayList

Summary If you think of a genericized type as a type, you won’t go far wrong Use it wherever a type would be used ArrayList myList becomes ArrayList myList new ArrayList() becomes new ArrayList () public ArrayList reverse(ArrayList list) becomes public ArrayList reverse(ArrayList list ) Advantage: Instead of having collections of “Objects”, you can control the type of object Disadvantage: more complex, more typing

The End