generic programming object type autoboxing bag of objects jcl collections nodes of objects ...

28
Generic Programming Generic Programming Object Type Object Type Autoboxing Autoboxing Bag of Objects Bag of Objects JCL JCL Collections Collections Nodes of Nodes of Objects Objects Iterators Iterators

Upload: dwight-dalton

Post on 13-Jan-2016

231 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Generic ProgrammingGeneric Programming

Object TypeObject Type AutoboxingAutoboxing Bag of ObjectsBag of Objects JCL CollectionsJCL Collections Nodes of ObjectsNodes of Objects IteratorsIterators

Page 2: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Ch. 5 Java Objects and IteratorsCh. 5 Java Objects and Iterators

Java’sJava’s Object Object typetype Wrapper classes for primitive data typesWrapper classes for primitive data types Objects collection is actually references Objects collection is actually references

collectioncollection Node object that contains object dataNode object that contains object data IteratorIterator

Page 3: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Need for Java’s Object type and genericsNeed for Java’s Object type and generics

Bag Bag Sequence Sequence StackStack ADTs and data structures where essentially the ADTs and data structures where essentially the

same design can be used for data of different same design can be used for data of different types (or even mixed types)types (or even mixed types)

for each typefor each type re-write essentially the same codere-write essentially the same code minimal modification with respect to the minimal modification with respect to the

type for this codetype for this code

Page 4: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Java’s Object typeJava’s Object type

Java’sJava’s Object class type provides a Object class type provides a possibility for writing one code and using it possibility for writing one code and using it for any type (or all typesfor any type (or all types

Page 5: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Object class and inheritanceObject class and inheritance

Every class in Java is directly or indirectly (if Every class in Java is directly or indirectly (if the class extends another class) derived from the class extends another class) derived from the Object class,, i.e., extending the Object the Object class,, i.e., extending the Object class. So, every object is an object of Object class. So, every object is an object of Object classclass

String s=new String(“Something”);String s=new String(“Something”);

Object obj;Object obj;

obj = s;obj = s;

Page 6: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Class type conversionClass type conversion

If an object is being treated as an object of Object If an object is being treated as an object of Object class, using this object reference we can not access class, using this object reference we can not access the methods and member variables defined in its the methods and member variables defined in its original class. original class.

The reference needs to be converted to the original The reference needs to be converted to the original type by castingtype by casting

String s=new String(“Something”);String s=new String(“Something”);

Object obj;Object obj;

obj = s;obj = s;

s= s= (String)(String) obj; obj;

Page 7: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Conversion of object referenceConversion of object reference

Widening conversion example:Widening conversion example: String str = new String (“Hello, World!”);String str = new String (“Hello, World!”); Object obj = str;Object obj = str; int stringLength = str.length( );int stringLength = str.length( );

stringLength = obj.length( );stringLength = obj.length( ); Narrowing conversion example:Narrowing conversion example: String string = (String) obj;String string = (String) obj; stringLength = string.length( );stringLength = string.length( );

Page 8: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Java 1.5 AutoboxingJava 1.5 Autoboxing

Java has 8 primitive (non-object) Java has 8 primitive (non-object) types of datatypes of data– integers: int, long, short, byteintegers: int, long, short, byte

– fractionals: double, floatfractionals: double, float

– logicals: booleanlogicals: boolean

– characters: charcharacters: char

Page 9: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Wrapper ClassesWrapper Classes

There are 8 classes in Java specifically There are 8 classes in Java specifically for making an object out of a value of for making an object out of a value of any of the primitive data type, and any of the primitive data type, and providing additional processing tools: providing additional processing tools: Integer Integer FloatFloat Long Long BooleanBoolean Short Short CharacterCharacter ByteByte DoubleDouble

Page 10: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Boxing and UnboxingBoxing and Unboxing

Autoboxing conversion – primitive value Autoboxing conversion – primitive value converted to a wrapper object of converted to a wrapper object of corresponding typecorresponding type

Unboxing – wrapper object is converted Unboxing – wrapper object is converted to corresponding primitveto corresponding primitve

Page 11: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Autoboxing and UnboxingAutoboxing and Unboxing

//boxing//boxing

int i = 42;int i = 42;

int j;int j;

Integer example;Integer example;

Example = new Integer(i);Example = new Integer(i);

j = example.intValue();j = example.intValue();

//autoboxing//autoboxing

example=i; //autoboxingexample=i; //autoboxing

j=example; //autounboxingj=example; //autounboxing

Page 12: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Objects exampleObjects example

Really collection of references to Really collection of references to objectsobjects

class ArrayBagclass ArrayBag object is a bag of objects of any typeobject is a bag of objects of any type implemented on an array of Object typeimplemented on an array of Object type Object [ ] data;Object [ ] data;

Page 13: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Java ObjectsJava Objects A collection of objects is actually a A collection of objects is actually a

collection of referencescollection of references to objects to objects Each element of the data array is aEach element of the data array is a

reference to an objectreference to an object Some of them may refer to the same Some of them may refer to the same

object:object:

Page 14: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Same Object reference exampleSame Object reference example

add the same reference into the bag add the same reference into the bag several timesseveral times

each time a copy of the reference is each time a copy of the reference is stored into a different position of the stored into a different position of the arrayarray

all are references to the same object, no all are references to the same object, no new copy of the actual object has ever new copy of the actual object has ever been madebeen made

Page 15: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

object equalityobject equality

== and != tests for objects == and != tests for objects only test if two references refer to the same only test if two references refer to the same

objectobject not if they have the same contentnot if they have the same content two distinct objects can have the same content.two distinct objects can have the same content. provide test of equality of contents, write an provide test of equality of contents, write an

equals method in which the object contents are equals method in which the object contents are comparedcompared

Page 16: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

null valuenull value

legal value for any class typelegal value for any class type most primitive data types have nothing similar. most primitive data types have nothing similar.

code with objects needs to deal with it code with objects needs to deal with it source of NullPointer-Exception source of NullPointer-Exception frustration, or error in answersfrustration, or error in answers

Page 17: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Node object that contain object dataNode object that contain object data

A node object can be used in a linked listA node object can be used in a linked list Instance variables of the IntNode classInstance variables of the IntNode class private int data;private int data; private IntNode link;private IntNode link; Instance variables of the general Node classInstance variables of the general Node class private Object data;private Object data; private IntNode linkprivate IntNode link;;

Page 18: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Generic method vs Object MethodGeneric method vs Object Method

static Object static Object middle(Object[]data)middle(Object[]data)

{{

if (data.length ==)if (data.length ==)

{return null;}{return null;}

elseelse

{return {return

data[data.length];}data[data.length];}

}}

static <T> T middle(T static <T> T middle(T []data)[]data)

{{

if (data.length ==)if (data.length ==)

{return null;}{return null;}

elseelse

{return {return

data[data.length];}data[data.length];}

}}

Page 19: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Generic method restrictionsGeneric method restrictions

Data type inferred must always be a Data type inferred must always be a class type (not a primitive)class type (not a primitive)

May not call a constructor for the May not call a constructor for the generic typegeneric type

Nor may you create a new array of Nor may you create a new array of element of that typeelement of that type

Page 20: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

GENERIC CLASSESGENERIC CLASSES

public class ArrayBag<E> implements Cloneablepublic class ArrayBag<E> implements Cloneable

{ private E[] data;{ private E[] data;

private int manyItems;private int manyItems;

}}

ArrayBag<String> sbag= new ArrayBag<String>();ArrayBag<String> sbag= new ArrayBag<String>();

ArrayBag<Integer> sbag= new ArrayBag<Integer>();ArrayBag<Integer> sbag= new ArrayBag<Integer>();

Page 21: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Generic Class RestrictionsGeneric Class Restrictions

Type used to instantiate must be a class Type used to instantiate must be a class [not primitive][not primitive]

Within class can’t call constructor for Within class can’t call constructor for generic type (nor make array of generic type (nor make array of elements of that type)elements of that type)

Page 22: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Array BagArray Bag

A generic bag classA generic bag class

http://southwestern.edu/~owensb/CS2Sp08/Lectures/NewBag/ArrayBag.javahttp://southwestern.edu/~owensb/CS2Sp08/Lectures/NewBag/ArrayBag.java A silly program to use itA silly program to use it

http://southwestern.edu/~owensb/CS2Sp08/Lectures/NewBag/Author.javahttp://southwestern.edu/~owensb/CS2Sp08/Lectures/NewBag/Author.java

Page 23: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Generic NodeGeneric Node

public class IntNodepublic class IntNode

{{

private int data;private int data;

IntNode linkeIntNode linke

}}

public class <E> Nodepublic class <E> Node

{{

private E data;private E data;

Node <E> linkNode <E> link

}}

Page 24: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

EqualsEquals

public static <E> Node<E> listSearch(Node<E> head, E target)public static <E> Node<E> listSearch(Node<E> head, E target) {{ Node<E> cursor;Node<E> cursor; if (target == null)if (target == null) { // Search for a node in which the data is the null reference.{ // Search for a node in which the data is the null reference. for (cursor = head; cursor != null; cursor = cursor.link)for (cursor = head; cursor != null; cursor = cursor.link) if (cursor.data == null)if (cursor.data == null) return cursor;return cursor; }} elseelse { // Search for a node that contains the non-null target.{ // Search for a node that contains the non-null target. for (cursor = head; cursor != null; cursor = cursor.link)for (cursor = head; cursor != null; cursor = cursor.link) if (target.equals(cursor.data))if (target.equals(cursor.data)) return cursor;return cursor; }} return null;return null; }}

Page 25: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Iterator and EnumerationIterator and Enumeration

Page 26: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Iterator CodeIterator Code

A class that implements the generic Iterator A class that implements the generic Iterator must provide these three methodsmust provide these three methods

public boolean hasNext ( );public boolean hasNext ( ); public E next ( );public E next ( ); public void remove ( );public void remove ( );

Page 27: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

Interface vs. ClassInterface vs. Class

interface methods are un-implemented originally

objects of an interface cannot be created, until some class implements this interface and its methods

then an object of this class can be used as an object of this interface

Page 28: Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators

InterfaceInterface

common standard shared between the common standard shared between the user/invoker of Java programs and the user/invoker of Java programs and the program designerprogram designer

documentation of an interface specifies documentation of an interface specifies clearly the properties of an object of this clearly the properties of an object of this interfaceinterface

whatever class the object belongs user can whatever class the object belongs user can use it confident of those propertiesuse it confident of those properties