1.10 working with objects v0.92

10
(c) 2006 National Academy for Software Development - http://academy.devbg.org 1 Working With Objects Working With Objects National Academy for National Academy for Software Development Software Development academy.devbg.org Miloslav Sredkov Miloslav Sredkov Contents Contents Contents 1. The class java.lang.Object 2. Equality and hash codes 3. Cloning, converting to String, finalizing 4. Type conversions 5. Autoboxing 1. 1. The class The class java.lang.Object java.lang.Object 2. 2. Equality and hash codes Equality and hash codes 3. 3. Cloning, converting to String, finalizing Cloning, converting to String, finalizing 4. 4. Type conversions Type conversions 5. 5. Autoboxing Autoboxing Class Class java.lang.Object java.lang.Object The Object Class The The Object Object Class Class Base class for all classes Defines the minimal requirements for all reference types Every java programmer should be familiar with them Only scalar types don’t inherit it However their wrapper classes do Base class for all classes Base class for all classes Defines the minimal requirements for all Defines the minimal requirements for all reference types reference types Every java programmer should be Every java programmer should be familiar with them familiar with them Only scalar types don Only scalar types don’ t inherit it t inherit it However their wrapper classes do However their wrapper classes do Object Members Object Object Members Members protected Object clone() public boolean equals(Object obj) public int hashCode() public String toString() protected void finalize() public Class<? extends Object> getClass() protected protected Object clone() Object clone() public public boolean boolean equals(Object equals(Object obj) obj) public public int int hashCode() hashCode() public public String toString() String toString() protected protected void void finalize() finalize() public public Class<? Class<? extends extends Object> Object> getClass() getClass() Object Members Object Object Members Members void notify() void notifyAll() void wait() void wait(long timeout) void wait(long timeout, int nanos) void void notify() notify() void void notifyAll() notifyAll() void void wait() wait() void void wait(long timeout) wait(long timeout) void void wait(long timeout, int wait(long timeout, int nanos nanos)

Upload: nb

Post on 14-Oct-2014

243 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 1

Working With ObjectsWorking With Objects

National Academy for National Academy for Software DevelopmentSoftware Development

academy.devbg.org

Miloslav SredkovMiloslav Sredkov

ContentsContentsContents

1. The class java.lang.Object

2. Equality and hash codes

3. Cloning, converting to String, finalizing

4. Type conversions

5. Autoboxing

1.1. The class The class java.lang.Objectjava.lang.Object

2.2. Equality and hash codesEquality and hash codes

3.3. Cloning, converting to String, finalizingCloning, converting to String, finalizing

4.4. Type conversionsType conversions

5.5. AutoboxingAutoboxing

Class Class java.lang.Objectjava.lang.Object

The Object ClassThe The ObjectObject ClassClass

• Base class for all classes

• Defines the minimal requirements for all reference types

• Every java programmer should be familiar with them

• Only scalar types don’t inherit it

• However their wrapper classes do

•• Base class for all classesBase class for all classes

•• Defines the minimal requirements for all Defines the minimal requirements for all reference typesreference types

•• Every java programmer should be Every java programmer should be familiar with themfamiliar with them

•• Only scalar types donOnly scalar types don ’’ t inherit itt inherit it

•• However their wrapper classes doHowever their wrapper classes do

Object MembersObjectObject MembersMembers

• protected Object clone()

• public boolean equals(Object obj)

• public int hashCode()

• public String toString()

• protected void finalize()

• public Class<? extends Object> getClass()

•• protectedprotected Object clone()Object clone()

•• publicpublic booleanboolean equals(Object equals(Object obj)obj)

•• publicpublic intint hashCode()hashCode()

•• publicpublic String toString()String toString()

•• protectedprotected voidvoid finalize()finalize()

•• publicpublic Class<? Class<? extendsextends Object> Object> getClass()getClass()

Object MembersObjectObject MembersMembers

• void notify()

• void notifyAll()

• void wait()

• void wait(long timeout)

• void wait(long timeout, int nanos)

•• voidvoid notify()notify()

•• voidvoid notifyAll()notifyAll()

•• voidvoid wait()wait()

•• voidvoid wait(long timeout)wait(long timeout)

•• voidvoid wait(long timeout, int wait(long timeout, int nanosnanos ))

Page 2: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 2

Equality and Hash Equality and Hash CodesCodes

Equality vs. IdentityEquality vs. IdentityEquality vs. Identity

• Identity:

– Operator ==

– References point to the same object

• Equality:

– .equals(Object) method

–Means that the objects represent the same abstract object

•• Identity:Identity:

–– Operator Operator ====

–– References point to the same objectReferences point to the same object

•• Equality:Equality:

–– .equals(Object).equals(Object) methodmethod

––Means that the objects represent the Means that the objects represent the same abstract objectsame abstract object

Equality ExampleEquality ExampleEquality Example

• Example:

• If you want to compare the objects use the .equals()

• If you want to check if the references point to the same object use ==

•• Example:Example:

•• If you want to compare the objects use If you want to compare the objects use the the .equals().equals()

•• If you want to check if the references If you want to check if the references point to the same object use point to the same object use ====

StringString aa == "fish";"fish";StringString bb == "fish";"fish";StringString cc == b;b;a.equals(b); //a.equals(b); // equality equality -- true;true;b == c; //b == c; // identity identity -- truetruea == b; //a == b; // identity identity –– maymay bebe truetrue oror falsefalse

Identity and EqualityIdentity and EqualityLive DemoLive Demo

equals() Methodequals() Methodequals() Method

• Should check whether the abstract objects represented by these objects are equal

• Cannot be invoked on null objects

• Reflexive: x.equals(x)

• Symmetric: (x.equals(y)==y.equals(x))

• Transitive: x.equals(y) && y.equals(z) => x.equals(z)

•• Should check whether the abstract Should check whether the abstract objects represented by these objects are objects represented by these objects are equalequal

•• Cannot be invoked on null objectsCannot be invoked on null objects

•• Reflexive: Reflexive: x.equals(x)x.equals(x)

•• Symmetric: Symmetric: ((x.equals(y)==y.equals(x))x.equals(y)==y.equals(x))

•• Transitive: Transitive: x.equals(y) && x.equals(y) && y.equals(z) => x.equals(z)y.equals(z) => x.equals(z)

equals() Methodequals() equals() MethodMethod

• Consistent : multiple invocations of x.equals(y) return the same if the objects are not modified

• x.equals(null) should return false

•• Consistent : multiple invocations of Consistent : multiple invocations of x.equals(y)x.equals(y) return the same if the return the same if the objects are not modifiedobjects are not modified

•• x.equals(x.equals( nullnull )) should return falseshould return false

Page 3: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 3

hashCode() MethodhashCode() hashCode() MethodMethod

• Should return number based on the properties of the abstract object represented by this object

• Two equal objects should have the same hash code

• a.equals(b) ? a.hashCode() == b.hashCode()

• a.hashCode() == b.hashCode() ? a.equals(b)

• collision: (!a.equals(b))&&a.hashCode()==b.hashCode()

• Collisions decrease performance

•• Should return number based on the properties Should return number based on the properties of the abstract object represented by this of the abstract object represented by this objectobject

•• Two equal objects should have the same hash Two equal objects should have the same hash codecode

•• a.equals(b) ? a.hashCode() == a.equals(b) ? a.hashCode() == b.hashCode()b.hashCode()

•• a.hashCode() == b.hashCode() ? a.hashCode() == b.hashCode() ? a.equals(b)a.equals(b)

•• collision: collision: (!(! a.equals(b))&&a.hashCodea.equals(b))&&a.hashCode ()==b.hashC()==b.hashCode()ode()

•• Collisions decrease performanceCollisions decrease performance

Default ImplementationsDefault ImplementationsDefault Implementations

• equals()

– most discriminating possible equivalence relation on objects

– x.equals(y) if x == y

• hashCode()

– returns int value based on the address of the object when overriding, override both!

•• equals()equals()

–– most discriminating possible most discriminating possible equivalence relation on objectsequivalence relation on objects

–– x.equals(y)x.equals(y) if if x == yx == y

•• hashCode()hashCode()

–– returns int value based on the address of returns int value based on the address of the object when overriding, override both!the object when overriding, override both!

Overriding Equals and Hash Code – ExampleOverriding Equals and Hash Overriding Equals and Hash Code Code –– ExampleExample

• Note that the following is not correct:•• Note that the following is not correct:Note that the following is not correct:

public class Pointpublic class Point {{private int x;private int x;private int y;private int y;public boolean equals(Objectpublic boolean equals(Object obj)obj) {{

//// correctcorrect behaviorbehavior onon nullnullif(obj instanceof Point)if(obj instanceof Point) {{

PointPoint o o == (Point)obj;(Point)obj;return x == o.x && y == o.y;return x == o.x && y == o.y;

}}return false;return false;

}}public int hashCode(){public int hashCode(){

return x * 20143 ^ y * 10169;return x * 20143 ^ y * 10169;}}

}}

public boolean equals Point o){public boolean equals Point o){return x == o.x && y == o.y;return x == o.x && y == o.y;

}}

Overriding Equals Overriding Equals and Hash Codeand Hash Code

Live DemoLive Demo

Cloning ObjectsCloning ObjectsCloneableCloneable interface and interface and

the the clone()clone() methodmethod

clone() Methodclone() clone() MethodMethod

• Should return a new object copy of the current

• Very useful when the exact type is not known

• Useless for immutable objects

• Usually:

– x.clone()!=x

– x.clone().getClass()==x.getClass()

– x.clone().equals(x)

• Interface Cloneable must be implemented

• Default implementation–shallow copy

•• Should return a new object copy of the currentShould return a new object copy of the current

•• Very useful when the exact type is not knownVery useful when the exact type is not known

•• Useless for immutable objectsUseless for immutable objects

•• Usually:Usually:

–– x.clone()!=xx.clone()!=x

–– x.clone().getClass()==x.getClass()x.clone().getClass()==x.getClass()

–– x.clone().equals(x)x.clone().equals(x)

•• Interface Interface CloneableCloneable must be implementedmust be implemented

•• Default implementationDefault implementation ––shallow copyshallow copy

Page 4: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 4

clone() Exampleclone() Exampleclone() Example

• Example:•• Example:Example:

public class Point implements Cloneable{public class Point implements Cloneable{private int x;private int x;private int y;private int y;

public Point(int x, int y){public Point(int x, int y){this.x=x;this.x=x;this.y=y;this.y=y;

}}......

}}

clone() Exampleclone() Exampleclone() Example

• Cloning manually:

• It is also correct to change return type:

•• Cloning manually:Cloning manually:

•• It is also correct to change return type:It is also correct to change return type:

public Point clone(){public Point clone(){return new Point(x,y);return new Point(x,y);

}}

public Point clone(){public Point clone(){return new Point(x,y);return new Point(x,y);

}}

clone() Exampleclone() Exampleclone() Example

• Or with Object.clone() :•• Or with Object.clone() :Or with Object.clone() :

public Objectpublic Object clone(){clone(){try {try {

return super.clone();return super.clone();} catch (CloneNotSupportedExceptione){} catch (CloneNotSupportedExceptione){

//// ShouldShould nevernever reachreach herehere becausebecause//// wewe implementimplement CloneableCloneable

e.printStrackTrace();e.printStrackTrace();return null;return null;}}

}}

Additional MethodsAdditional MethodstoStringtoString ()()

finalize()finalize()

toString() MethodtoString() toString() MethodMethod

• String representation of the object

• May not contain the whole state information

• Should be a concise but informative

• Recommended that all classes override this method

• Default implementation:

•• String representation of the objectString representation of the object

•• May not contain the whole state May not contain the whole state informationinformation

•• Should be a concise but informativeShould be a concise but informative

•• Recommended that all classes override Recommended that all classes override this methodthis method

•• Default implementation:Default implementation:returnreturn getClass().getNamegetClass().getName () + '@'() + '@'

+ Integer.toHexString(hashCode());+ Integer.toHexString(hashCode());

toString() ExampletoString() ExampletoString() Example

• With concatenation:

• With format():

•• With concatenation:With concatenation:

•• With With format()format() ::

public String public String toStringtoString (){(){return "return " Point("+x+","+yPoint("+x+","+y +")";+")";

}}

public String toString(){public String toString(){return String.format(return String.format(

"Student(fn=%d, name=%s)","Student(fn=%d, name=%s)",fn, name);fn, name);

}}

Page 5: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 5

finalize() Methodfinalize() finalize() MethodMethod

• Something like destructor in other languages

• Java does not support destructors!

• Called before the object is garbage collected

• No guarantee as to when this will happen!

• May not happen before the program exits!

• May be used to free resources (open files, connections)

• Should be combined with other method, such as close() or dispose()

•• Something like destructor in other languagesSomething like destructor in other languages

•• Java does not support destructors!Java does not support destructors!

•• Called before the object is garbage collectedCalled before the object is garbage collected

•• No guarantee as to when this will happen!No guarantee as to when this will happen!

•• May not happen before the program exits!May not happen before the program exits!

•• May be used to free resources (open files, May be used to free resources (open files, connections)connections)

•• Should be combined with other method, such Should be combined with other method, such as as close()close() or or dispose()dispose()

finalize() Examplefinalize() Examplefinalize() Example

• Example:•• Example:Example:class ResourceHolder{class ResourceHolder{

private private ImportantResourceImportantResource resource;resource;......public void close(){public void close(){

if(resource.isOpen()){if(resource.isOpen()){resource.close();resource.close();

}}}}

public void finalize(){public void finalize(){close();close();

}}}}

clone()clone() and and toString()toString()

Live DemoLive Demo

Comparing ObjectsComparing ObjectsComparableComparable and and

ComparatorComparator interfacesinterfaces

Comparable InterfaceComparable InterfaceComparable Interface

• This interface imposes a total ordering on the objects of each class that implements it

• Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort)

•• This interface imposes a total ordering This interface imposes a total ordering on the objects of each class that on the objects of each class that implements it implements it

•• Lists (and arrays) of objects that Lists (and arrays) of objects that implement this interface can be sorted implement this interface can be sorted automatically by Collections.sort (and automatically by Collections.sort (and Arrays.sort)Arrays.sort)

Comparable Interface –ExampleComparable Interface Comparable Interface ––ExampleExample

• Example:•• Example:Example:public class Student implements Comparable{public class Student implements Comparable{

private String firstName;private String firstName;private String lastName;private String lastName;private int age;private int age;

public int getAge() {public int getAge() {return age;return age;

}}public void setAge(int age) {public void setAge(int age) {

this.age = age;this.age = age;}}public String getFirstName() {public String getFirstName() {

return firstName;return firstName;}}public void setFirstName(String firstName) {public void setFirstName(String firstName) {

this.firstName = firstName;this.firstName = firstName;}}

Page 6: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 6

Comparable Interface –ExampleComparable Interface Comparable Interface ––ExampleExample

public String getLastName() {public String getLastName() {return lastName;return lastName;

}}

public void setLastName(String lastName) {public void setLastName(String lastName) {this.lastName = lastName;this.lastName = lastName;

}}

public int compareTo(Object student) {public int compareTo(Object student) {If(!(student instanceof Student)){If(!(student instanceof Student)){throw new ClassCastException("A Student throw new ClassCastException("A Student

objectobject expected.");expected.");}}int studentAge = ((Student) int studentAge = ((Student)

student).getAge();student).getAge();return this.agereturn this.age -- studentAge;studentAge;

}}

}}

Comparable Interface –ExampleComparable Interface Comparable Interface ––ExampleExample

public String getLastName() {public String getLastName() {return lastName;return lastName;

}}

public void setLastName(String lastName) {public void setLastName(String lastName) {this.lastName = lastName;this.lastName = lastName;

}}

public int compareTo(Object student) {public int compareTo(Object student) {ii f(!(student instanceof Student)){f(!(student instanceof Student)){

throw new ClassCastException("A Student throw new ClassCastException("A Student object expected.");object expected.");

}}int studentAge = ((Student)student).getAge();int studentAge = ((Student)student).getAge();

return this.agereturn this.age -- studentAge;studentAge;}}

}}

Comparator InterfaceComparator InterfaceComparator Interface

• Objects are sometimes comparable in many ways

• In cases like this, create a Comparator that defines how to compare two objects

• To make objects comparable in two ways, then you need two comparators

•• OObjects are sometimes comparable in bjects are sometimes comparable in many waysmany ways

•• In cases like this, create a Comparator In cases like this, create a Comparator that defines how to compare two objectsthat defines how to compare two objects

•• To make objects comparable in two To make objects comparable in two ways, then you need two comparatorsways, then you need two comparators

Comparator Interface –ExampleComparator Interface Comparator Interface ––ExampleExample

public class LastNameComparator implements Comparat or {public class LastNameComparator implements Comparat or {public int compare(Object student1, Object student2 ) {public int compare(Object student1, Object student2 ) {

String lastName1 = String lastName1 = ((Student) student1).getLastName().toUpperCase();((Student) student1).getLastName().toUpperCase();

String firstName1 = String firstName1 = ((Student) student1).getFirstName().toUpperCase();((Student) student1).getFirstName().toUpperCase();

String lastName2 = String lastName2 = ((Student) student2).getLastName().toUpperCase();((Student) student2).getLastName().toUpperCase();

String firstName2 = String firstName2 = ((Student) student2).getFirstName().toUpperCase();((Student) student2).getFirstName().toUpperCase();

if (!(lastName1.equals(lastName2)))if (!(lastName1.equals(lastName2))) {{return lastName1.compareTo(lastName2);return lastName1.compareTo(lastName2);

}} elseelse {{return firstName1.compareTo(firstName2);return firstName1.compareTo(firstName2);

}}}}

}}

Comparable and Comparable and ComparatorComparator

Live DemoLive Demo

Type conversionsType conversions

Page 7: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 7

Type CastingType CastingType Casting

• The (Type) operator

• Cannot be redefined

• May be used between primitive types

• May be used to cast between subclass and superclass

• Other usages are not allowed!

•• The (Type) operatorThe (Type) operator

•• Cannot be redefinedCannot be redefined

•• May be used between primitive typesMay be used between primitive types

•• May be used to cast between subclass May be used to cast between subclass and superclassand superclass

•• Other usages are not allowed!Other usages are not allowed!

Primitive TypesPrimitive TypesPrimitive Types

• Automatic conversion is performed in the following order:

byte -> short -> int -> long -> float -> double

• Note that accuracy may be lost when converting to floating point types

• char may be converted automatically to int, long, float, and double

• The result of arithmetic operations with byteand short is int!

• In all other cases explicit conversion is needed

•• Automatic conversion is performed in the Automatic conversion is performed in the following order:following order:

bytebyte --> > shortshort --> > intint --> > longlong --> > floatfloat --> > doubledouble

•• Note that accuracy may be lost when Note that accuracy may be lost when converting to floating point typesconverting to floating point types

•• charchar may be converted automatically to int, may be converted automatically to int, longlong , , floatfloat , and , and doubledouble

•• The result of arithmetic operations with The result of arithmetic operations with bytebyteand and shortshort is is intint !!

•• In all other cases explicit conversion is neededIn all other cases explicit conversion is needed

Primitive Types ExamplePrimitive Types ExamplePrimitive Types Example

int i = 5;int i = 5;

// float f = 5.5; error// float f = 5.5; errorfloat f = 5.5f;float f = 5.5f;

//i = f; error//i = f; errori = (int) f; // ok, i = 5i = (int) f; // ok, i = 5f = i; //ok, f=5f = i; //ok, f=5

byte b = 5;byte b = 5;short s = 10;short s = 10;

//b = b + b; error//b = b + b; error//b=(byte) b + b; still error//b=(byte) b + b; still error

b = (byte) (b + b); //okb = (byte) (b + b); //ok

//s=b+b;error//s=b+b;error

Primitive Types ExamplePrimitive Types ExamplePrimitive Types Example

//s=b+b;error//s=b+b;error

s = (short) (b + b); //oks = (short) (b + b); //ok

double d = f; //okdouble d = f; //okdd = b; //ok= b; //ok

char c = char c = ’’ AA’’ ;;

s = c; //errors = c; //errori = c; //ok,i=65i = c; //ok,i=65i = c * c * c; //oki=274625i = c * c * c; //oki=274625

long l = i * i; //bad,l=long l = i * i; //bad,l= -- 18905207031890520703long l2=(long) i * i; //l2=75418890625long l2=(long) i * i; //l2=75418890625

float f2=l2; //f2=75418894336float f2=l2; //f2=75418894336

Primitive TypesPrimitive TypesLive DemoLive Demo

To Superclass/InterfaceTo Superclass/InterfaceTo Superclass/Interface

• Automatic conversion is performed when object has to be used as some of its supertypes

• You can assign every object to Object variable

• You can pass everything as Object argument

• Explicit casting is still allowed and may be used to improve readability or to invoke another overload of a method.

•• Automatic conversion is performed Automatic conversion is performed when object has to be used as some of when object has to be used as some of its supertypesits supertypes

•• You can assign every object to Object You can assign every object to Object variablevariable

•• You can pass everything as Object You can pass everything as Object argumentargument

•• Explicit casting is still allowed and may Explicit casting is still allowed and may be used to improve readability or to be used to improve readability or to invoke another overload of a method.invoke another overload of a method.

Page 8: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 8

To Superclass/InterfaceTo Superclass/InterfaceTo Superclass/Interface

public class Point extends Objectpublic class Point extends Objectimplements Cloneable,Comparable{implements Cloneable,Comparable{

......}}

public class Test {public class Test {

public static void public static void main(Stringmain(String [] [] argsargs ) {) {

PointPoint p= new Point(3,p= new Point(3, 2);2);ObjectObject oo == p;p;CloneableCloneable cc == p;p;ArrayListArrayList listlist = new ArrayList();= new ArrayList();list.add(o); //list.add(o); // nono castingcastinglist.add(p); //list.add(p); // PointtoObjectPointtoObjectlist.add(c); //list.add(c); // CloneabletoObjectCloneabletoObject

}}

}}

Casting to SubtypeCasting to SubtypeCasting to Subtype

• Casting to subtype must be done explicitly

• It is dangerous but sometimes necessary

• Has to be done when overriding some Object methods

• If the object is not from the given subtype exception is thrown

• If you perform too much conversions to subtype you should review the design

• Generics reduce the number of necessary subtype conversions

•• Casting to subtype must be done explicitlyCasting to subtype must be done explicitly

•• It is dangerous but sometimes necessaryIt is dangerous but sometimes necessary

•• Has to be done when overriding some Object Has to be done when overriding some Object methodsmethods

•• If the object is not from the given subtype If the object is not from the given subtype exception is thrownexception is thrown

•• If you perform too much conversions to If you perform too much conversions to subtype you should review the designsubtype you should review the design

•• Generics reduce the number of necessary Generics reduce the number of necessary subtype conversionssubtype conversions

Casting to SubtypeCasting to SubtypeCasting to Subtype

• It is also necessary when using not generic collections:

•• It is also necessary when using not It is also necessary when using not generic collections:generic collections:

PointPoint p= new Point(2,p= new Point(2, 5);5);ArrayListArrayList listlist = new ArrayList();= new ArrayList();

list.add(p);list.add(p);//// PointPoint qq == list.get(0);list.get(0); //// compilecompile errorerrorPointPoint qq == (Point)list.get(0);(Point)list.get(0);CloneableCloneable cc == (Cloneable)list.get(0);(Cloneable)list.get(0);StringString ss == (String)list.get(0); //exception(String)list.get(0); //exception

Scalars vs. ObjectsScalars vs. ObjectsBoxing, Autoboxing, Boxing, Autoboxing,

UnboxingUnboxing

Wrapper ClassesWrapper ClassesWrapper Classes

• For each scalar type there is a wrapper class

• Wrapper classes are immutable

• They provide lots of methods for manipulation of the corresponding scalar type

• They provide useful constants such as Integer.MIN_VALUE,Integer.MAX_VALUE

• They support interning with the valueOf()method

•• For each scalar type there is a wrapper For each scalar type there is a wrapper classclass

•• Wrapper classes are immutableWrapper classes are immutable

•• They provide lots of methods for They provide lots of methods for manipulation of the corresponding manipulation of the corresponding scalar typescalar type

•• They provide useful constants such as They provide useful constants such as Integer.Integer. MIN_VALUEMIN_VALUE ,Integer.,Integer. MAX_VALUEMAX_VALUE

•• They support interning with the They support interning with the valueOf()valueOf()methodmethod

The Old Way of BoxingThe Old Way of BoxingThe Old Way of Boxing

• Primitive types ( int , short , long ...) are not objects

• They are not acceptable as Object parameters

• To put int in collection you had to box it:list.add(new Integer(i))

• To get int from a collection you had to unbox it:int x = (Integer)c.get(key).intValue();

•• Primitive types (Primitive types ( intint , , shortshort , , longlong ...) are ...) are not objectsnot objects

•• They are not acceptable as Object They are not acceptable as Object parametersparameters

•• To put int in collection you had to box it:To put int in collection you had to box it:list.add(list.add( newnew Integer(i))Integer(i))

•• To get int from a collection you had to To get int from a collection you had to unbox it:unbox it:intint x = x = (( Integer)c.get(key).intValueInteger)c.get(key).intValue ();();

Page 9: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 9

AutoboxingAutoboxingAutoboxing

• Autoboxing is added in Java 5

• You can pass a primitive type as argument instead of its wrapper class or Object

• You can assign primitive type to a variable of its wrapper class

• Boxing is done behind the scene

• Boxing decreases performance!

(this is valid for both auto and manual boxing!)

•• AutoboxingAutoboxing is added in Java 5is added in Java 5

•• You can pass a primitive type as You can pass a primitive type as argument instead of its wrapper class or argument instead of its wrapper class or ObjectObject

•• You can assign primitive type to a You can assign primitive type to a variable of its wrapper classvariable of its wrapper class

•• Boxing is done behind the sceneBoxing is done behind the scene

•• Boxing decreases performance!Boxing decreases performance!

(this is valid for both auto and manual (this is valid for both auto and manual boxing!)boxing!)

UnboxingUnboxingUnboxing

• You can pass an object of the wrapper class as argument instead of its corresponding primitive type

• You can assign an object of the wrapper class primitive type to a variable of its wrapper class

• You can perform arithmetic operations with objects of the wrapper classes

• Unboxing is done transparently

•• You can pass an object of the wrapper You can pass an object of the wrapper class as argument instead of its class as argument instead of its corresponding primitive typecorresponding primitive type

•• You can assign an object of the wrapper You can assign an object of the wrapper class primitive type to a variable of its class primitive type to a variable of its wrapper classwrapper class

•• You can perform arithmetic operations You can perform arithmetic operations with objects of the wrapper classeswith objects of the wrapper classes

•• Unboxing is done transparentlyUnboxing is done transparently

Boxing MapBoxing MapBoxing Map

CharacterCharactercharchar

BooleanBooleanbooleanboolean

DoubleDoubledoubledouble

FloatFloatfloatfloat

LongLonglonglong

IntegerIntegerintint

ShortShortshortshort

ByteBytebytebyteClassClassScalarScalar

Autoboxing ExampleAutoboxing ExampleAutoboxing Example

• Counting the word frequency:•• Counting the word frequency:Counting the word frequency:

public static void main(String[]args){public static void main(String[]args){Map<String,Integer>Map<String,Integer> mm ==

newnew TreeMap<String,Integer>();TreeMap<String,Integer>();for (Stringfor (String wordword :: args){args){

IntegerInteger freqfreq == m.get(word);m.get(word);m.put(word,m.put(word,

freq== null ? 1 : freq + 1);freq== null ? 1 : freq + 1);}}System.out.println(m);System.out.println(m);

}}

Autoboxing ExampleAutoboxing ExampleAutoboxing Example

• List adapter for int array:•• List adapter for int array:List adapter for int array:public static List<Integer>public static List<Integer> asList(asList(

final int[]final int[] a){a){return new AbstractList<Integer>(){return new AbstractList<Integer>(){

public Integerpublic Integer get(int i){get(int i){return a[i];return a[i];

}}//// NotNot workingworking ifif valval ==== nullnullpublic Integerpublic Integer set(set( int i,int i, IntegerInteger val){val){

IntegerInteger oldValoldVal == a[i];a[i];a[i] = val;a[i] = val;return oldVal;return oldVal;

}}public int size(){public int size(){

return a.length;return a.length;}}

};};}}}}

RecommendationsRecommendationsRecommendations

• Override the appropriate Object methods depending on how your class will be used

• Follow the recommendations strictly!

• Think that the user of your objects may not know their type

• If these methods are not enough implement additional like equalsIgnoreCase(), md5HashCode(), deepToString()

•• Override the appropriate Object methods Override the appropriate Object methods depending on how your class will be depending on how your class will be usedused

•• Follow the recommendations strictly!Follow the recommendations strictly!

•• Think that the user of your objects may Think that the user of your objects may not know their typenot know their type

•• If these methods are not enough If these methods are not enough implement additional like implement additional like equalsIgnoreCaseequalsIgnoreCase (), md5HashCode(), (), md5HashCode(), deepToStringdeepToString ()()

Page 10: 1.10 Working With Objects v0.92

(c) 2006 National Academy for Software Development - http://academy.devbg.org 10

Working With ObjectsWorking With ObjectsWorking With Objects

Questions?Questions?Questions?

ProblemsProblemsProblems

1. Comment the following equals and hashCode implementations:

1.1. Comment the following equals and hashCode Comment the following equals and hashCode implementations:implementations:

returnreturn x == obj.x && y == obj.y;x == obj.x && y == obj.y;returnreturn x ^ y;x ^ y;

returnreturn x == obj.x && y == obj.y;x == obj.x && y == obj.y;returnreturn x;x;

returnreturn x == obj.x;x == obj.x;returnreturn x;x;

returnreturn falsefalse ;;returnreturn 0;0;

return return truetrue ;;returnreturn 0;0;

return return thisthis ==obj;==obj;defaultdefault

return return thisthis ==obj;==obj;returnreturn 0;0;

defaultdefaultreturnreturn 5;5;

equals()equals()hashCode()hashCode()

ProblemsProblemsProblems

2. When is the clone() method usable?

3. If you implement a collection class, how will you implement toString()

4. Will it be necessary for a collection class to override the finalize() method?

5. If you have classes CartesianPoint and PolarPoint which both inherit Point , how will you make conversions between them?

2.2. When is the When is the clone()clone() method usable?method usable?

3.3. If you implement a collection class, how will If you implement a collection class, how will you implement you implement toString()toString()

4.4. Will it be necessary for a collection class to Will it be necessary for a collection class to override the override the finalize()finalize() method?method?

5.5. If you have classes If you have classes CartesianPointCartesianPoint and and PolarPointPolarPoint which both inherit which both inherit PointPoint , how , how will you make conversions between them?will you make conversions between them?

ProblemsProblemsProblems

6. Create a class which overrides the finalize() method to print a message to the standard output. Allocate some object and experiment with System.gc() . Try to finalize the objects without it.

7. Create a class representing a Customer (names and address only) and override all Object methods except the synchronization ones.

8. Try to store and access some of the objects in HashMap.

9. Try to make your objects usable in TreeMap

6.6. Create a class which overrides the Create a class which overrides the finalize()finalize() method to print a message to method to print a message to the standard output. Allocate some object the standard output. Allocate some object and experiment with and experiment with System.gc()System.gc() . Try to . Try to finalize the objects without it.finalize the objects without it.

7.7. Create a class representing a Customer Create a class representing a Customer (names and address only) and override all (names and address only) and override all ObjectObject methods except the synchronization methods except the synchronization ones.ones.

8.8. Try to store and access some of the objects Try to store and access some of the objects in in HashMapHashMap..

9.9. Try to make your objects usable in Try to make your objects usable in TreeMapTreeMap