Thursday, March 3, 2011

Overriding hash code and equals in collections


package SDMXDatabaseUploader;

import java.util.HashMap;


public class SDMXSeries {
public HashMap SeriesKey = new HashMap();

public HashMap Obs = new HashMap();
/**
* Since SeriesKeys have to be unique this is
* what defines if an SDMXSeries equals another.
*/

public boolean equals(Object o){
SDMXSeries comparison = (SDMXSeries)o;
return SeriesKey.equals(comparison.SeriesKey);

}
/**
*
*/
public int hashCode(){
return SeriesKey.hashCode();

}

/**
*
* @param key
* @param value
* @throws NullPointerException if key or value is null.
* @throws DuplicateKeyException if key is repeated.
*/
public void addSeriesKeyValue(String key, String value)throws NullPointerException, DuplicateKeyException{

if (key == null || value == null)throw new NullPointerException("Key or Value is null");
if (SeriesKey.containsKey(key))throw new DuplicateKeyException("Failed trying to add a duplicate key to the series key" + key);
SeriesKey.put(key, value);

}
/**
*
* @param key
* @param value
* @throws NullPointerException if key or value is null.
* @throws DuplicateKeyException if key is repeated.
*/
public void addObsKeyValue(String key, String value)throws NullPointerException, DuplicateKeyException{

if (key == null || value == null)throw new NullPointerException("Key or Value is null");
if (Obs.containsKey(key))throw new DuplicateKeyException("Failed Trying to add a duplicate key to the series key" + key);
Obs.put(key, value);
}
public String toString(){
return SeriesKey.toString() + " " + Obs.toString();

}
}


Exception code...


package SDMXDatabaseUploader;

public class DuplicateKeyException extends Exception {

/**
*
*/
private static final long serialVersionUID = 1L;
public DuplicateKeyException (String message){
super(message);
}
public DuplicateKeyException (){
super("Failed attempting to add duplicate key.");

}

}

package SDMXDatabaseUploader;

public class EmptyValueException extends Exception {
public EmptyValueException (int lineNumber){
super("Processed Line "+ lineNumber +"has an empty string for one or more entries.");
}

}

No comments:

Post a Comment