Link to home
Start Free TrialLog in
Avatar of jstakk
jstakkFlag for Norway

asked on

Container for different primitive types and type casting

Using java 6, I want to create a class that will contain a two dimensional arrays of different types. It should work for int, double and boolean types, and it should have methods for getting this array as another type.

I tried doing this using generics, but I'm not sure if this is the best way. When using generics i'm not able to use primitive types. And when I use wrapper classes type casting is not that easy. I cannot cast from Integer to Double.

Any suggestions to how I can do this a better way?

public class ArrayContainer<T>
{
 
	protected T[][] array;
 
	public ArrayContainer( T[][] array)
	{
		this.array = array;
	}
 
	public T[][] getArray()
	{
		return array;
	}
 
	public void setArray( T[][] pattern )
	{
		this.pattern = pattern;
	}
	
	public Double[][] getArrayAsDouble()
	{
		if (arrayinstanceof Double[][])
		{
			return (Double[][]) array;
		}
		else if (array instanceof Integer[][])
		{
			return (IntegerToDouble(array));
		}
                .....
 
		return null;
	}
 
       public int getArraryAsInt()
       {
       }
	protected Double[][] IntegerToDouble(T[][] values) 
	{
	    ....
	}
	.....
}

Open in new window

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You can't cast arrays. You'd need to create an array of the correct type and copy the elements
Avatar of jstakk

ASKER

Yes I know. But I still can't cast each element directly from Integer to Double.

This should be done to very large arrays, so it has to be efficient.
Integer i = new Integer(1000);
Double d = (double) (int) i;

Open in new window

You can do new Double(i) surely...?

Or you could have Class arrayClass = Object.class and have a setClass(Class class) method. Then just call setClass(Integer.class) and in your setValues you can check the values being entered are instanceof class
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jstakk

ASKER

@hazgoduk: The constructor for Double takes either a double, or a String as argument. Using an Integer in the constructor will work but it will call the Integer's toString() method and then parse the string. Not very efficient. Your second suggestion is perhaps a good way to go, i'll look into that. Thank you.

@CEHJ:
Thats what I was looking for. Looks like a good solution to my problem. I'm gonna try it out.

Thank you both very much for you quick and good help.
Why would you need a 'setClass' method?
I must admit I didn't look at the code very much as I just woke up! You would indeed not need a setClass method. Just set the class based on the type sent in the contructor
:-)