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 ,


public boolean equals(Object other){
throw new UnsupportedOperationException();
}
Contract of Equals Method:
The equals method must be
  • reflexive
  • transitive
  • symmetric
  • comapring with a null object should be false
So say if we want to compare two Point Objects


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 && (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

Dividing a Sequence into K ranges

Problem Statement:
Say you have a sequence of N numbers and you want to partition the sequence into K groups such that after applying a cost function c(i) for each group the sum of all cost functions over all groups is minimized or maximized?

Approach:
To divide the sequence into ranges , we will use K keys . The key used to divide the group can be indices or values . If its values then numbers in the
sequence can be used along with values in the sequence to partition values into groups whose key is K.

One way to do this is to use K-for loops , if the key is value based then probable something like this would work:


for i = 1 to n
for j = 1 to n
for k = 1 to n
for l = 1 to n{
key1 = seq[i]
key2 = seq[j]
key3 = seq[k]
key4 = seq[l]

}


After dividing the sequence into keys, use the keys to apply and aggregate the result of individual cost functions . Depending upon the requirement reduce the cost functions using functions like min , max depending upon if you want to minimize or maximize your result.

There you go , now u have 1 simple way of dividing a sequence into groups

Thursday, November 16, 2006

binding Source n Combo box initialization problem



I was trying to bind a combo box to a list of items . Now each item is a domain object .

myBindingSource.DataSource = my list of domain objects

i create a binding between the SelectedItem property of the combo box and the property Value of my domain object in the binding source .

now initially when the value of my domain object is null , i want an empty row to appear in the combo box , which works fine . Now as i choose different domain object values in the combo box , the value of the domain object is not refreshed .

I was using myComboBox_SelectedIndexChanged event to notify of the change in domain object value , but it was not helping the refreshing of other entities that depended on the values of the domain object .

So now instead of the SelectedIndexChanged Event now i use the
myBindingSource_CurrentChanged event and it works like a charm

Monday, November 06, 2006

a neat ToString for c++




template <class T>
string to_string(T toBeConverted){

// create an out string stream
ostringstream buffer;
// write the value to be converted to the output stream
buffer << toBeConverted;
// get the string value
return buffer.str();
}

Monday, September 18, 2006

as in C#

The keyword as in c# prevents the InvalidCastException From happening , its default behaviour is to nullify the object being casted . When the object being casted is used it thwrows a Null Exception .

Thursday, September 14, 2006

splitting strings in c++ using stringstream

of if you need to split a string "10 20 30 40 " in c++

You can do that using istringstream

all u need to do is

#include < sstream >

Assuming s is "10 20 30 40"

istringstream iss(s) ;

int ten , twenty , thirty , forty ;
iss >> ten >> twenty >> thirty >> forty;

converting 2D array into single array

This piece of snippet is written in c++ , converts a 2 dimensional Array into a single array
//
provide the size of the array to be converted with T being the data type
// invoke the function like


// int * arr = Covert2DTo1DimensionalArray ( source_array , 3 , 3 )



template < class T , int SIZE >
T* Covert2DTo1DimensionalArray( T source[SIZE][SIZE] , int width , int height ){

// the width of the new single dimensional array would be width * height
int length = width * height;

// create a new single simensional array on the heap
T * _array = new T[length];

// push values into the single dimensional array

int ctr = 0;

for(int y = 0; y <= height ; y++) {
for( int x = 0; x <= width; x++) {
_array[ctr++] = source[y][x];
}
}
return _array;
}

Wednesday, September 06, 2006

ComboBox DataSource And Refresh Issues

How many times have you been frustrated by the fact , that you set the DataSource on a
ComboBox and it does Not show up or it does not Refresh .

basically,
code like
myComboBox.DataSource = value

does not update the values on screen

the workaround to get this working though not elegant is :

BindingManagerBase manager = myComboBox.BindingContext(value);
manager.SuspendBinding();
myComboBox.DataSource = value;
manager.ResumeBinding();

Sunday, August 27, 2006

Generating uniqu GUIDS in MS Sql Server

Use NewId() to generate new unique guids .

Stupid MS Sql Server Logon failure

The So called MS Sql Server throws up a ERROR 1069 : Logon failure everytime you change indows password .

The way to get it working is :

o correct the password in Microsoft Windows 2000 Server and Microsoft Windows XP:
1.Click Start, point to Settings, and then click Control Panel.
2.Double-click Administrative Tools, and then double-click Services.
3.Use one of the following steps based on your instance type:
For a default instance of SQL Server, double-click MSSQLServer, and then click the Log On tab.
For a named instance of SQL Server, double-click MSSQL$YourInstanceName, and then click the Log On tab. Replace YourInstanceName with the actual name of the SQL Server instance.
For a default instance of SQL Server Agent, double-click SQLAgent, and then click the Log On tab.
For a named instance of SQL Server Agent, double-click SQLAgent$YourInstanceName, and then click the Log On tab. Replace YourInstanceName with the actual name of the SQL Server instance.
4.Type the correct password in the Password and Confirm password textbox, and then click OK.

Friday, August 25, 2006

ListBox SurprizEEE !!

.net Listbox is quirky . I was trying to set an ArrayList as the datasource of my list box .

my code looked like :

_list = new ArrayList();
myListBox.DataSource = _list;


I thought that once i Add or Remove entries to this list . It would reflect that automatically reflect and update it on the listbox view . But to my surprize that doesnt work so .

The way to get this working is :

everytime you change list u need to reset the Datasource , speaking in terms of code that means , u need to write somethin like

myListBox.DataSource = new ArrayList();
myListbox.DataSource = list;

you have to do this everytime you change the list.