Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Return value of Custom object in HashMap

807605Jul 4 2007 — edited Jul 4 2007
I have created a custom object (TableValue) that should represent the key value in aHashMap. When reading data from a file, the custom object should be either a String or a Double. I want the custom object to return the proper type. That is, I am trying to avoid the use of an Object as a key value in the HashMap. However, I want TableValue to return the proper value. Some example code is listed below. My question is this, how do I get TableValue to return the proper type?

Thanks
import java.util.HashMap;

public class Table {

HashMap<TableValue,Frequency>table=new HashMap<TableValue,Frequency>();
	
	
	public void count(TableValue aElement){
		Frequency fq=table.get(aElement);
		if(fq==null){
			fq=new Frequency();
			table.put(aElement, fq);
		}else{
			fq.add();
		}
	}
	
	public double getCount(TableValue aElement){
		Frequency fq=table.get(aElement);
		if(fq==null){
			return 0.0;
		}else{
			return fq.getFrequency();
		}
	}
	
	
	public static void main(String[] args) {
		Table tab=new Table();
		tab.count(new TableValue("s"));
		tab.count(new TableValue(5.0));
	}

}




public class TableValue {
	
	private double dValue;
	private String sValue;
	private boolean isDouble=false;
	
	public TableValue(Object o){
		try{
			if(o.getClass().getName().equals("java.lang.String")){
				sValue=(String)o;
			}else if(o.getClass().getName().equals("java.lang.Double")){
				dValue=(Double)o;
			}
		}catch(ClassCastException ex){
			
		}
	}
	
        //next two methods not correct, can not overload like this
	public double getValue(){
		//want to return a double
		return dValue;
	}
	
	public String getValue(){
		//want to returna string
		return sValue;
	}

}


public class Frequency {

	private double total, cummulativeFrequency;
	
	public Frequency(){
		total = 1.0;
		cummulativeFrequency = 0.0;
	}
	
	public void add(){
		total++;
		cummulativeFrequency++;
	}
	
	public void addCummulativeFrequency(double aLowerCount){
		cummulativeFrequency += aLowerCount;
	}
	
	public double getFrequency(){
		return total;
	}
	
	public double getCummulativeFrequency(){
		return cummulativeFrequency;
	}
	
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 1 2007
Added on Jul 4 2007
6 comments
620 views