The java concurrent framework provides Semaphore . Semaphores are useful when the end user wants to implement some kind of resource pool.
In a semaphore permits can be acquired and released . A semaphore when created can be initialized with the number of entries it can contain at any point of time .
Semaphore s = new Semaphore(N);
// acquire a permit
s.acquire();
// release a permit
s.release();
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Thursday, March 20, 2008
Java Concurrent Programming : CountDownLatch
CountDownLatch in the concurrent programming framework provided by java is pretty cool.
In principle it works like a binary latch . (Once set it remain in that state for ever )
So when would something like a countdownlatch be useful for thread programming .
Consider a scenario , you have a big task T to be done by N threads .
1) Now you want all the threads to be started at the same time so that they get equal opportunity
to participate in the completion of the task .
2) You want your main thread to do something when all the threads finish .
You can create two CountDownLatch objects.
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch endLatch = new CountDownLatch(N);
Then you can construct all the threads like this
Thread thread = new Thread(){
public void run(){
try{
startLatch.await();
// do the task
endLatch.countDown();
}catch(InterruptedException e){
Thread.currentThread.interrupt();
}
}
}
thread.start();
so when the thread starts it will block cause of the CountDownLatch (await method call)
when startLatch.countDown() is called the latch opens and all the threads can flow now and start working .
similarly the main thread that is waiting for all threads to finish .
will continue when all the threads have called endLatch.countDown()
In principle it works like a binary latch . (Once set it remain in that state for ever )
So when would something like a countdownlatch be useful for thread programming .
Consider a scenario , you have a big task T to be done by N threads .
1) Now you want all the threads to be started at the same time so that they get equal opportunity
to participate in the completion of the task .
2) You want your main thread to do something when all the threads finish .
You can create two CountDownLatch objects.
CountDownLatch startLatch = new CountDownLatch(1);
CountDownLatch endLatch = new CountDownLatch(N);
Then you can construct all the threads like this
Thread thread = new Thread(){
public void run(){
try{
startLatch.await();
// do the task
endLatch.countDown();
}catch(InterruptedException e){
Thread.currentThread.interrupt();
}
}
}
thread.start();
so when the thread starts it will block cause of the CountDownLatch (await method call)
when startLatch.countDown() is called the latch opens and all the threads can flow now and start working .
similarly the main thread that is waiting for all threads to finish .
will continue when all the threads have called endLatch.countDown()
Sunday, March 09, 2008
Java : Inner Classes and Parent Reference Escaping
When an inner class is created inside a class in java, it transparently contains a reference to its parent class. If by chance this reference leaks out , it compromises the thread safety of the parent class. To avoid these kind of issues , factory methods should be used to create inner classes .
Another thing that should be best avoided is : starting of a thread inside the constructor of a class.
Since the thread object also shares the reference to its parent class, this reference might be in an inconsistent state when the thread is started .
To prevent these type of scenarios factory methods are best.
e.g
public class Prent {
private childThread;
private Parent(){
childThread = new Thread();
}
public static Parent newInstance(){
Parent parent = new Parent();
childThread.start();
return parent
}
}
Another thing that should be best avoided is : starting of a thread inside the constructor of a class.
Since the thread object also shares the reference to its parent class, this reference might be in an inconsistent state when the thread is started .
To prevent these type of scenarios factory methods are best.
e.g
public class Prent {
private childThread;
private Parent(){
childThread = new Thread();
}
public static Parent newInstance(){
Parent parent = new Parent();
childThread.start();
return parent
}
}
Tuesday, February 05, 2008
Remove from Array : Java Quickie
lets say you have a problem . You have an array of N numbers . You want to remove the i th number . Then you need a new array not containing the j th number . You are using java . How can you do it ??
Here 's a quickie:
int[] result = null;
result = new int[n-1];
if(i > 0 ) System.arraycopy(array,0,result,0,i);
if(i+1 < n ) System.arraycopy(array,i+1,result,i,n-1-i);
}
This is quick way of removing the element you need and getting a new array devoid of the removed number .
Here 's a quickie:
int[] result = null;
result = new int[n-1];
if(i > 0 ) System.arraycopy(array,0,result,0,i);
if(i+1 < n ) System.arraycopy(array,i+1,result,i,n-1-i);
}
This is quick way of removing the element you need and getting a new array devoid of the removed number .
Monday, November 26, 2007
What would happen if locks in Java were non re-entrant
Locks in java are re-entrant , that aids locking to work effectively with Object Oriented Programming . Why ??
Just consider , if you have a base class
class Mybase{
public synchronized doStuff(){
}
}
Now If you have a child class extending the base class then,
public class MyChild extends MyBase{
public synchronized doStuff(){
super.doStuff();
}
}
This would cause a deadlock . Why ??
When on the child doStuff is called a lock on the MyBase object is obtained . Now in MyChild::doStuff when super.doStuff() is called the code would again try to get a new lock on
Mybase and if locks were non re-entrant then the thread would block and hence would cause a deadlock.
Just consider , if you have a base class
class Mybase{
public synchronized doStuff(){
}
}
Now If you have a child class extending the base class then,
public class MyChild extends MyBase{
public synchronized doStuff(){
super.doStuff();
}
}
This would cause a deadlock . Why ??
When on the child doStuff is called a lock on the MyBase object is obtained . Now in MyChild::doStuff when super.doStuff() is called the code would again try to get a new lock on
Mybase and if locks were non re-entrant then the thread would block and hence would cause a deadlock.
Tuesday, October 30, 2007
Private lock Object Idiom
The private lock object idiom is generally used in making a class Thread Safe.
Instead of using the instance of the object as a lock object an internal private object is used
as a lock object.
private Object lock = new Object();
so the method need to acquire a lock should use the lock object instead of this object.
e.g.
public void foo(){
synchronized(lock){
....
}
}
Instead of using the instance of the object as a lock object an internal private object is used
as a lock object.
private Object lock = new Object();
so the method need to acquire a lock should use the lock object instead of this object.
e.g.
public void foo(){
synchronized(lock){
....
}
}
Sunday, October 21, 2007
Lazy Initailization Idioms
Double check idiom is supposedly the best lazy initialization technique
private static Foo foo = null;
public static void getFoo(){
if (null == foo){
synchronized (Foo.class){
if ( null == foo){
foo = new Foo();
}
}
}
return foo;
}
This is the double check idiom , it works great with primitives but is flawed when it
comes to object references cause the behaviour of object references after synchronized is
undefined.
Solution 1:
private static Foo foo = new Foo();
public static void getFoo(){
return foo;
}
Solution 2:
private static Foo foo = null;
public synchronized Foo getFoo(){
if (null == Foo)
foo = new Foo();
return foo;
}
Solution 3:
Initialize on demand - holder class Idiom
private static class Holder{
static Foo foo = new Foo();
}
public static Foo getFoo(){
return Holder.foo;
}
private static Foo foo = null;
public static void getFoo(){
if (null == foo){
synchronized (Foo.class){
if ( null == foo){
foo = new Foo();
}
}
}
return foo;
}
This is the double check idiom , it works great with primitives but is flawed when it
comes to object references cause the behaviour of object references after synchronized is
undefined.
Solution 1:
private static Foo foo = new Foo();
public static void getFoo(){
return foo;
}
Solution 2:
private static Foo foo = null;
public synchronized Foo getFoo(){
if (null == Foo)
foo = new Foo();
return foo;
}
Solution 3:
Initialize on demand - holder class Idiom
private static class Holder{
static Foo foo = new Foo();
}
public static Foo getFoo(){
return Holder.foo;
}
Thursday, October 18, 2007
Finalizer guardian Idiom
Finalizer Guardian idiom is nothing but an anonymous class assigned to a private final instance variable within a class that wants to override the finalize method .
The anonymous class takes the responsibility of calling the finalize method of the enclosing class.
All this in code looks like :
public class A{
private final Object b = new Object(){
protected void finalize() throws Throwable {
// finalize the outer A here
}
};
}
The anonymous class takes the responsibility of calling the finalize method of the enclosing class.
All this in code looks like :
public class A{
private final Object b = new Object(){
protected void finalize() throws Throwable {
// finalize the outer A here
}
};
}
Tuesday, August 21, 2007
Showing an Eclipse View Programatically
In eclipse non savable containers are called views . It pretty easy to create a view , all you need to do is to implement an extension - point (org.eclipse.ui.views) and add features to a class . If you want to implement your own view , you can google it you 'll find a number of articles about it .
In this blog entry i tell you how to show/hide an existing view programatically .
Scenario1 : Assuming you have created a view whose view ID is "my.view" and you want to show this view .
Scenario2: You know the view id of some view and you want to show that view programatically.
IWorkbench workbench = PLatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
workbenchWindow.getActivePage().showView("my.view");
// to hide a view
workbenchWindow.getActivePage().hideView("my.view");
PlatformUI is a plugin that can give information about currently active windows and objects in an eclipse session . Its available to us so we use it to get the current workbench window . In eclipse workbench window is the main window . Each window has one or more pages . We get the active page . In the active page we either show or hide the view we are interested in .
In this blog entry i tell you how to show/hide an existing view programatically .
Scenario1 : Assuming you have created a view whose view ID is "my.view" and you want to show this view .
Scenario2: You know the view id of some view and you want to show that view programatically.
IWorkbench workbench = PLatformUI.getWorkbench();
IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
workbenchWindow.getActivePage().showView("my.view");
// to hide a view
workbenchWindow.getActivePage().hideView("my.view");
PlatformUI is a plugin that can give information about currently active windows and objects in an eclipse session . Its available to us so we use it to get the current workbench window . In eclipse workbench window is the main window . Each window has one or more pages . We get the active page . In the active page we either show or hide the view we are interested in .
Monday, July 09, 2007
Extension Object Pattern : an Eclipse Example
In short an Extension Object pattern is a nice way of extending an interface of class by 3 rd party classes without polluting the base interface of the class.
I am going to take eclipse as an example to explaing this pattern . For those of you , who have done eclipse plugin development . You would have come across ed the interface IAdaptable. This interface is at heart of the Extension Object Pattern implemented by Eclipse .
So what is the Extension Object Pattern ???
Say you have an interface IFile . This interface represents an abstraction of a file . Apart from being a basic file this IFile interface could offer many services . So the question is how do you offer those services .
One simple way would be to extend the IFile interface . Add the extra functionality to the new new interface and have come class implement that new interface . e.g you could have a IUIFile interface . Once you have that interface , you could implement that interface .
But the problem with that approach is that , you end up polluting the base beautiful interface and have a bloated class ( implementor) . Well the above mentioned approach would work if you are fine with extending the object every time you want to implement a new service , but as the number of services increase the class becomes super duper bloated monster .
So how does the extension object pattern help us in solving this evolution problem ??
I ll continue with the IFile interface from eclipse to explain how can we go about using the interface to implement the extension pattern .
We know that IFile might have to support a number of services at some point of time in future . So rather than have IFile implement all the new interfaces , we just implement the IAdaptable interface . This interface is a place holder , saying that the class implementing IFile is now ready to be extended by 3 rd party classes without polluting the base interface IFile.
This Adaptable interface can contain a simple method that does the job of resolving the service to the correct service provider .
public interface IFile extends IAdaptable , .... {
.....
public Object getAdapter(Class adapter);
...
}
}
Now lets say that we want to check if IFile supports ServiceA , or ServiceB.
We can do that now passing ServiceA.class to the getAdpater method .
This method would return a valid object if the service is supported or on the other hand it would return a null object .
Instead of having a number of if conditions in the getAdapter method what eclipse does is that for each interface supported by the type , eclipse creates an adapter factory . The different factories are then registered with an AdapterManager . The getAdapter method then returns
the appropriate AdapterFactory via the AdpaterManager. e.g
public Object getAdapter(Class adapter);
return Platform.getAdapterManager.getAdpater(this,adapter);
}
Something like this can later be used to return the right adapter for intended service.
public interface IAdapterfactory {
public Object getAdapter(Object adaptableObject, Class adapterType);
....
}
The adapter manager uses different adapter factories to resolve the reference for the asked interface , for the given type .
So in this manner multiple behaviors can be added to a single type . This is a nice way to support class extensions.
I am going to take eclipse as an example to explaing this pattern . For those of you , who have done eclipse plugin development . You would have come across ed the interface IAdaptable. This interface is at heart of the Extension Object Pattern implemented by Eclipse .
So what is the Extension Object Pattern ???
Say you have an interface IFile . This interface represents an abstraction of a file . Apart from being a basic file this IFile interface could offer many services . So the question is how do you offer those services .
One simple way would be to extend the IFile interface . Add the extra functionality to the new new interface and have come class implement that new interface . e.g you could have a IUIFile interface . Once you have that interface , you could implement that interface .
But the problem with that approach is that , you end up polluting the base beautiful interface and have a bloated class ( implementor) . Well the above mentioned approach would work if you are fine with extending the object every time you want to implement a new service , but as the number of services increase the class becomes super duper bloated monster .
So how does the extension object pattern help us in solving this evolution problem ??
I ll continue with the IFile interface from eclipse to explain how can we go about using the interface to implement the extension pattern .
We know that IFile might have to support a number of services at some point of time in future . So rather than have IFile implement all the new interfaces , we just implement the IAdaptable interface . This interface is a place holder , saying that the class implementing IFile is now ready to be extended by 3 rd party classes without polluting the base interface IFile.
This Adaptable interface can contain a simple method that does the job of resolving the service to the correct service provider .
public interface IFile extends IAdaptable , .... {
.....
public Object getAdapter(Class adapter);
...
}
}
Now lets say that we want to check if IFile supports ServiceA , or ServiceB.
We can do that now passing ServiceA.class to the getAdpater method .
This method would return a valid object if the service is supported or on the other hand it would return a null object .
Instead of having a number of if conditions in the getAdapter method what eclipse does is that for each interface supported by the type , eclipse creates an adapter factory . The different factories are then registered with an AdapterManager . The getAdapter method then returns
the appropriate AdapterFactory via the AdpaterManager. e.g
public Object getAdapter(Class adapter);
return Platform.getAdapterManager.getAdpater(this,adapter);
}
Something like this can later be used to return the right adapter for intended service.
public interface IAdapterfactory {
public Object getAdapter(Object adaptableObject, Class adapterType);
....
}
The adapter manager uses different adapter factories to resolve the reference for the asked interface , for the given type .
So in this manner multiple behaviors can be added to a single type . This is a nice way to support class extensions.
Friday, June 29, 2007
Logging using the Eclipse Logging Framework
if you are using eclipse in your day to day work and you want to log activities using the in built eclipse logging frame work .
Here is a small example to do the same ,
if u have a plugin class then say MyPlugin that extends AbstrarctUIPlugin then u can a have method in that class that does the logging for you .
public static void log(String message , int status ){
getDefault().getLog().log(new Status(status, getPluginID( ), message,null) );
}
the values , status can take are like :
Here is a small example to do the same ,
if u have a plugin class then say MyPlugin that extends AbstrarctUIPlugin then u can a have method in that class that does the logging for you .
public static void log(String message , int status ){
getDefault().getLog().log(new Status(status, getPluginID( ), message,null) );
}
the values , status can take are like :
- IStatus.ERROR
- IStatus.WARNING
Thursday, June 28, 2007
Immutable Objects In Java
What is an Immutable Object ?
An immutable object is an object that does not change its state once its created .Java has a number of inbuilt classes that provide that functionality e.g String , Integer etc..
So how do you create an immutable object :
public class Complex {
public Complex(int real, int imaginery){
this.real = real;
this.imaginery = imaginery;
}
public Complex add(Complex left , Complex right) {
// fuctional return
return new Complex(left.real + right.real , left.imaginery + right.imaginery);
}
}
The advantage of having an immutable class is that its thread safe.
The disadvantage being creating many new objects for different operations can lead to memory bloat
An immutable object is an object that does not change its state once its created .Java has a number of inbuilt classes that provide that functionality e.g String , Integer etc..
So how do you create an immutable object :
- Remove or make setters less accessible.
- Preveting methods from getting overriden.
- Make all fields final.
- Make defensive copies of mutable objects.
- Do not provide a clone method
- Do not provide a copy constructor
- return a fuctional object
public class Complex {
public Complex(int real, int imaginery){
this.real = real;
this.imaginery = imaginery;
}
public Complex add(Complex left , Complex right) {
// fuctional return
return new Complex(left.real + right.real , left.imaginery + right.imaginery);
}
}
The advantage of having an immutable class is that its thread safe.
The disadvantage being creating many new objects for different operations can lead to memory bloat
Little Sugar ( Mixins in Java)
Mixin ?? what is a mixin ...
Thats what i wondered when i cam accross the phrase . A Mixin is a way of adding features to the core functionlaity of a class . It is different from extending the class , cause it generally pertains to adding features not related to the core or default behaviour of a class .
A little example will make things clear . Say you have a small class Person that represents a person wholly . Not if you want to compare 2 instances of Person , you could implement the Comparable interface . By implementing the Comparable interface you add a functionlity that is not directly related to a Person object but is a help ful feature .
So a simple way to implement a Mixin is to implement an interface .. so much for buzz words...
Thats what i wondered when i cam accross the phrase . A Mixin is a way of adding features to the core functionlaity of a class . It is different from extending the class , cause it generally pertains to adding features not related to the core or default behaviour of a class .
A little example will make things clear . Say you have a small class Person that represents a person wholly . Not if you want to compare 2 instances of Person , you could implement the Comparable interface . By implementing the Comparable interface you add a functionlity that is not directly related to a Person object but is a help ful feature .
So a simple way to implement a Mixin is to implement an interface .. so much for buzz words...
Wednesday, June 27, 2007
Little Sugar (Security Manager , Java)
Today i ll gloss over a few small things worth remembering about security
in java . So lets get started :
In Java , we hava a Java API . The java API provides us with a lot methods to accomplish different type of tasks . Now if for some reason we want to enforce security on these tasks so that only selected operation can be performed and that to by selected users . In that case we need to create a security policy file.
In the security policy file , we specifiy how permissions are applied to different code sources . We specify differnt permissions in terms of Permission objects that are applied to CodeSource objects .
At runtime a policy object is created corresponding to the policy file .
For the policies to take effect a SecurityManager needs to be installed . Once the security manager is installed it uses the AccessController ,which inturn checks the different permissions based on different permission objects .
When the class loader loads a type in the JVM . It places the type in a protection domain , which encapsulates the permissions . At runtime , when methods on the type instance are invoked the security manger is checked to see if the method can be invoked .
in java . So lets get started :
In Java , we hava a Java API . The java API provides us with a lot methods to accomplish different type of tasks . Now if for some reason we want to enforce security on these tasks so that only selected operation can be performed and that to by selected users . In that case we need to create a security policy file.
In the security policy file , we specifiy how permissions are applied to different code sources . We specify differnt permissions in terms of Permission objects that are applied to CodeSource objects .
At runtime a policy object is created corresponding to the policy file .
For the policies to take effect a SecurityManager needs to be installed . Once the security manager is installed it uses the AccessController ,which inturn checks the different permissions based on different permission objects .
When the class loader loads a type in the JVM . It places the type in a protection domain , which encapsulates the permissions . At runtime , when methods on the type instance are invoked the security manger is checked to see if the method can be invoked .
Tuesday, June 19, 2007
Litttle Sugar (Java Collections)
The other day I was reading about java collections . I came accross this trivial point about Sets in java that is worth remembering . In java there are 3 different implementations of the Set interface , namely :
The fastest among the 3 implementations , but does not maintain ordering.
TreeSet:
The slowest among the 3 implementations , uses red black tree to internally store items and orders the items by value.
LinkedHashSet:
Its performance comes in between the 1st two but maintain the ordering in which items are
inserted . Uses hashtable with linked list to store items.
- HashSet
- TreeSet
- LinkedHashSet
The fastest among the 3 implementations , but does not maintain ordering.
TreeSet:
The slowest among the 3 implementations , uses red black tree to internally store items and orders the items by value.
LinkedHashSet:
Its performance comes in between the 1st two but maintain the ordering in which items are
inserted . Uses hashtable with linked list to store items.
Friday, June 08, 2007
Little Sugar (Compound Assignment operator And Implicit Type Conversion)
x += i
'+=' This is what is called the compound assignment operator in Java . An interesting thing about this operator is that , this operator automatically casts the type of expression on the right , which in this case is i to the type of the expression on the left which being x .
'+=' This is what is called the compound assignment operator in Java . An interesting thing about this operator is that , this operator automatically casts the type of expression on the right , which in this case is i to the type of the expression on the left which being x .
Tuesday, June 05, 2007
Little Sugar 1 ( Java)
So often i come across something cool , but important so i thought using blogging about them would be nice idea , so here is my Little Sugar 1
when converting from 1 type to another , sign extension is performed if the source data is signed
eg
byte b = 0xff;
char c = (char) b
if the type is char , no sign conversion is peformed .
if converting from byte to char if no sign conversion is required than bitwise AND with 0xff is nice idea.
char c = (char) b & 0xff
when converting from 1 type to another , sign extension is performed if the source data is signed
eg
byte b = 0xff;
char c = (char) b
if the type is char , no sign conversion is peformed .
if converting from byte to char if no sign conversion is required than bitwise AND with 0xff is nice idea.
char c = (char) b & 0xff
Contract of Object.Hashcode in Java
In continuation with my ongoing summary series , today i am going to write about hashcode and objects in java . So lets get started .
The contract of hashcode in java
Well if you dont do that , then different instances of the object when stored into the hashtable , hashmap will be stored into the same hash bucket and when that happens all objects actually end up being stored in a linked list and hence cause drastically effect the performance of the program.
So what would be a good way of implementing the hashcode , well a simple way would be to pick a prime number and multiply it with the hashcode of all the fields , for primitive fields this would be their values
So let me give you a simple example , so if u have a class that has say two fields , field1 and field2 then the hashcode for that object can be
Choosing an i odd prime number reduces the chances of overflows . For immutable objects where calculating hashcode , might be an expensive process it makes sense to store the hashcode locally and to return the pre calculated hashcode value.
The contract of hashcode in java
- Inrrespective of the number of times hashcode is invoked on an object , it should return the same value.
- If two objects are equal then the hashcode values should also be the same.
Well if you dont do that , then different instances of the object when stored into the hashtable , hashmap will be stored into the same hash bucket and when that happens all objects actually end up being stored in a linked list and hence cause drastically effect the performance of the program.
So what would be a good way of implementing the hashcode , well a simple way would be to pick a prime number and multiply it with the hashcode of all the fields , for primitive fields this would be their values
So let me give you a simple example , so if u have a class that has say two fields , field1 and field2 then the hashcode for that object can be
public int hashCode(){
int result = 17;
result += 37 * field1;
result += 37 * field2;
return result;
}
Choosing an i odd prime number reduces the chances of overflows . For immutable objects where calculating hashcode , might be an expensive process it makes sense to store the hashcode locally and to return the pre calculated hashcode value.
Saturday, June 02, 2007
How to override the equals method in Java
Well the other day i was reading about how to override the equals method in java . Here is brief summary of what i learnt .
Never Assume Anything:
First things first if you are writing a class whose equals method u have not overridden assumi ng that the equals method would never be called . never assume anything and atleast throw a UnsupportedOperationException to prevent others from doing a equality check on the instance of your class.
In terms of Code the equals method in your class should look like ,
The equals method must be
Now ok i ve implemented a hypothetical Point class that has only 1 member entity called x . That entity is an Object rather than being a primitive type.
if(point == this)
return true;
In this line i check the references are equals , if they are then can we can skip other checking cause basically they are the same two references .
if(!point instanceof Point)
return false;
Second we make sure the object that we are comparing against is of the same type and is not null . The not null is implicit in the behaviour of instanceof operator . The instanceof operator makes sure that object on the left is not null othwerise it returns false.
Point other = (Point) point;
Next we perform the casting to the type of this object so that we can check each and every field .
boolean result = true;
result = result &&amp; (x != null && x.equals(other.x));
Next since x is the field being used here , we check if x is not null and if its not null we see if its equal to the x field in the other Object.
return result;
Finally we return the result
Never Assume Anything:
First things first if you are writing a class whose equals method u have not overridden assumi ng that the equals method would never be called . never assume anything and atleast throw a UnsupportedOperationException to prevent others from doing a equality check on the instance of your class.
In terms of Code the equals method in your class should look like ,
Contract of Equals Method:
public boolean equals(Object other){
throw new UnsupportedOperationException();
}
The equals method must be
- reflexive
- transitive
- symmetric
- comapring with a null object should be false
public class Point {
private Object x;
public Point( Object x ) {
this.x = x;
}
public boolean equals(Object point){
if(point == this)
return true;
if(!point instanceof Point)
return false;
Point other = (Point) point;
boolean result = true;
result = result && (x == other.x || (x != null && x.equals(other.x)));
return result;
}
}
Now ok i ve implemented a hypothetical Point class that has only 1 member entity called x . That entity is an Object rather than being a primitive type.
if(point == this)
return true;
In this line i check the references are equals , if they are then can we can skip other checking cause basically they are the same two references .
if(!point instanceof Point)
return false;
Second we make sure the object that we are comparing against is of the same type and is not null . The not null is implicit in the behaviour of instanceof operator . The instanceof operator makes sure that object on the left is not null othwerise it returns false.
Point other = (Point) point;
Next we perform the casting to the type of this object so that we can check each and every field .
boolean result = true;
result = result &&amp; (x != null && x.equals(other.x));
Next since x is the field being used here , we check if x is not null and if its not null we see if its equal to the x field in the other Object.
return result;
Finally we return the result
Subscribe to:
Posts (Atom)
Labels
. linux
(1)
algorithm
(15)
analytics
(1)
bash
(2)
bigoh
(1)
bruteforce
(1)
c#
(1)
c++
(40)
collections
(1)
commands
(2)
const
(1)
cosine similarity
(1)
creating projects
(1)
daemon
(1)
device_drivers
(1)
eclipse
(6)
eclipse-plugin-development
(9)
equals
(1)
formatting
(1)
freebsd
(1)
game programming
(1)
hashcode
(1)
heap
(1)
heaps
(1)
immutable-objects
(1)
java
(19)
JDT
(1)
kernel
(1)
linux
(4)
little sugar
(23)
logging
(1)
machine learning
(1)
marker-resolution
(1)
markers
(1)
mergesort
(1)
mixins
(1)
numbers
(1)
opengl
(2)
patterns
(2)
priority-queue
(1)
programming
(51)
ps
(1)
ranking
(1)
refactoring
(3)
references
(1)
security
(1)
set
(1)
shell
(1)
similarity
(1)
statistics
(1)
stl
(1)
tetris
(1)
threads
(1)
trees
(2)
unicode
(1)
unix
(2)
views
(2)
windows programming
(2)
XNA
(1)