How to convert entire double[] array into an Object - java

I have a function in a jar file which accepts two parameters:
An Object array which mentions the type and number of output
An Object array which contains input to the function.
The input I need to pass consists of 7 objects. I have to send two double[] arrays and rest all 5 are double values.
I would like to know how to convert double[] into an Object.
Please help me with this.
If i want to convert a single double value to an object of Double, I can use the following code.
public class JavadoubleToDoubleExample {
public static void main(String[] args) {
double d = 10.56;
/*
Use Double constructor to convert double primitive type to a Double object.
*/
Double dObj = new Double(d);
System.out.println(dObj);
}
}
Output:
10.56
But what if the d={1.0,8.9,4.0,7.9}.
How can I convert the array into an object of Double?

Arrays are already Objects in Java. If you want to convert an array of primitive double into an array of Objects:
double[] nums = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7};
Object[] objs = new Object[nums.length];
for(int i=0; i<nums.length; i++)
objs[i] = new Double(nums[i]);

Related

Datatypes in Java and their representation

I have question about primitive types in Java (int, double, long, etc).
Question one:
Is there a way in Java to have a datatype, lets say XType (Lossless type) that can hold any of the primitive types?
Example of hypothetical usage:
int x = 10;
double y = 9.5;
XType newTypeX = x;
XType newTypeY = y;
int m = newTypeX;
Question two:
Is there away to tell from the bits if this number (primitive type) is an integer, or a double, or a float, etc?
You can use the Number class, which is the super class for all numeric primitive wrapper classes, in your first snippet:
int x = 10;
double y = 9.5;
Number newTypeX = x;
Number newTypeY = y;
The conversion between the primitive types (int, double) and the object type (Number) is possible through a feature called autoboxing. However, this line won't compile:
int m = newTypeX;
because you cannot assign the super type variable into an int. The compiler doesn't know the exact type of newTypeX here (even if it was assigned with an int value earlier); for all it cares, the variable could as well be a double.
For getting the runtime type of the Number variable, you can e.g. use the getClass method:
System.out.println(newTypeX.getClass());
System.out.println(newTypeY.getClass());
When used with the example snippet, this will print out
class java.lang.Integer
class java.lang.Double
Well, you can do something like this:
Integer i = 1;
Float f = 2f;
Object[] obArr = new Object[]{i, f};
Float fReconstruct = (Float) obArr[2]
Not really primitive types, but the closest you can get!
Regarding to your first question, for those you can use the Number class.
You can use an Object to hold reference to any of these types, but it will be 'boxed' to it's wrapper (int will be hold as an Integer, long as a Long, etc.)...
Not yet (java 8), and not in the way you want to get the primitive value back. But if instead of holding a primitive type you hold a primitive type wrapper (which are classes that descend from the Object class and wrap their corresponding primitive, i.e. Byte wraps byte, Integer wraps int, Long wraps long, etc), then you could do this:
public class Holder<T extends Number> {
private final T number;
public Holder(T number) {
this.number = number;
}
public T get() {
return this.number;
}
}
You could use this Holder class to hold an instance of any subclass of Number, including primitive types wrappers. For example:
Holder<Integer> holderX = new Holder<>(5);
Holder<Double> holderY = new Holder<>(1.234);
int x = holderX.get(); // 5
double y = holderY.get(); // 1.234
The above is possible because of a feature of Java called Generics, along with another feature called autoboxing.
Extending generics to support primitive types is being considered for Java 9 or 10 (not sure), under the term Specialization. In theory, this would allow you to have:
List<int> list = new ArrayList<int>();
Here is a draft.
Generics are a facility of generic programming that were added to the Java programming language in 2004 within J2SE 5.0. They allow "a type or method to operate on objects of various types while providing compile-time type safety.
For an example I like the one on tutorialspoint:
public class GenericMethodTest
{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
// Display array elements
for ( E element : inputArray ){
System.out.printf( "%s ", element );
}
System.out.println();
}
public static void main( String args[] )
{
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println( "Array integerArray contains:" );
printArray( intArray ); // pass an Integer array
System.out.println( "\nArray doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( "\nArray characterArray contains:" );
printArray( charArray ); // pass a Character array
}
}
This would produce the following result:
Array integerArray contains:
1 2 3 4 5 6
Array doubleArray contains:
1.1 2.2 3.3 4.4
Array characterArray contains:
H E L L O Array integerArray contains:
1 2 3 4 5 6
Array doubleArray contains:
1.1 2.2 3.3 4.4
Array characterArray contains:
H E L L O
For more on this link.

[D cannot be cast to java.lang.Double

I wrote below code. It get this message:
Exception in thread "main" java.lang.ClassCastException: [D cannot be cast to java.lang.Double
double[] xyz = {1, 11, 111, 2, 22, 222};
ArrayList array = new ArrayList();
array.add(xyz);
double[] vals = new double[array.size()];
vals[0] = (double) array.get(0);
vals[1] = (double) array.get(1);
vals[2] = (double) array.get(2);
I have also search and see some post on Stack Overflow, but they do not make much me sense. What should I do?
If you want to add an array of double values to an ArrayList, do this:
Double[] xyz = {...};
ArrayList<Double> array = new ArrayList<>(); // note, use a generic list
array.addAll(Arrays.asList(xyz));
A List cannot store primitives, so you must store Double values not double. If you have an existing double[] variable, you can use ArrayUtils.toObject() to convert it.
Actually your problem is that you are trying to cast the type of 'xyz', which does not seems to be a double or the Wrapper associed (Double), into a double.
Since java can't transform the type of 'xyz' into a double a ClassCastException is throw. You should try to add n double to your array like that (or even in a loop) :
ArrayList<Double> myListOfDouble = new ArrayList();
myListOfDouble.add(1.0);
And then using a for loop to populate your double[] vals like this :
for(int i = 0; i < myListOfDouble.size(); i++)
vals[i] = myListOfDouble.get(i);

How to create a list of doubles out of an array of doubles

First off, I want to say that I know this has been asked before at the following location (among others), but I have not had any success with the answers there:
Create ArrayList from array
What I am trying to do is the following:
double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
List<Double> FFTMagnitudeList = Arrays.asList(FFTMagnitudeArray);
audioData.setProperty("FFTMagnitudeList", FFTMagnitudeList);
However, I get the error:
"Type mismatch: cannot convert from List<double[]> to List<Double>"
This makes no sense to me, as I thought the List was necessary and the Array.asList(double[]) would return a list of Double, not double[]. I have also tried the following, to no avail:
List<Double> FFTMagnitudeList = new ArrayList<Double>();
FFTMagnitudeList.addAll(Arrays.asList(FFTMagnitudeArray));
List<Double> FFTMagnitudeList = new ArrayList<Double>(Arrays.asList(FFTMagnitudeArray));
And I keep getting the same error.
So how do I create the List?
Change your method to return the object wrapper array type.
Double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
List<Double> FFTMagnitudeList = Arrays.asList(FFTMagnitudeArray);
Or you'll have to manually copy from the primitive to the wrapper type (for the List).
double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
List<Double> FFTMagnitudeList = new ArrayList<>(FFTMagnitudeArray.length);
for (double val : FFTMagnitudeArray) {
FFTMagnitudeList.add(val);
}
The double type is a primitive type and not an object. Arrays.asList expects an array of objects. When you pass the array of double elements to the method, and since arrays are considered as objects, the method would read the argument as an array of the double[] object type.
You can have the array element set the Double wrapper type.
Double[] FFTMagnitudeArray = processAudio.processFFT(audioData);
Using Java 8:
List<Double> FFTMagnitudeList = Arrays.stream(FFTMagnitudeArray).mapToObj(Double::valueOf).collect(Collectors.toCollection(ArrayList::new));
This creates a DoubleStream (a stream of the primitive type double) out of the array, uses a mapping which converts each double to Double (using Double.valueOf()), and then collects the resulting stream of Double into an ArrayList.

create a java array of double (primitive) in matlab

I would like to be able to declare a java array of double in matlab. In java you would do something like this:
double[] arr = new double[4];
Now I want to do the same thing in Matlab. I have tried the following:
arr = javaArray('D', 100);
arr = javaArray('[D', 100);
It gives me the No class [D can be located on the java class path error.
I know I can create an array of Double with arr = javaArray('com.lang.Double', 100);, but this is not a primitive type and would require further conversion.

Paramertized Types

I am from a .Net background and do not understand the following snip. Can someone explain the <> and the following code to me as I just dont seem to get it. Sorry for dumb questions but this one I have been trying to understand all evening.
List<double[]> x = new ArrayList<double[]>();
for (int i = 0; i < 3; i++) {
x.add(new double[] { 1, 2, 3, 4, 5, 6 });
}
They're the equivalent of C# generics. It's creating a list of double arrays, then adding [1,2,3,4,5,6] to it three times.
If you create a List<T> you can add instance of T to the list. In this case, T is double[].
In the Java programming language arrays are objects and may be assigned to variables of type java.lang.Object. Your code can also be written this way
Object numbers =new double[] { 1, 2,
3, 4, 5, 6 };
Your code
List<double[]> x = new ArrayList<double[]>();
for (int i = 0; i < 3; i++) {
x.add(numbers);
}
Another variation: Here I created "x" as a List that can contain Object types. Since, arrays are subclasses of Object in Java, I can store the arrays in this list "x"
List<Object> x=new ArrayList<Object>();
for (int i = 0; i < 3; i++) {
x.add(numbers);
}
For a list, the type parameter in the <>'s indicates what type of objects should be stored in that list. List<double []> creates a list that stores arrays of doubles.
List<double []> myList = new ArrayList<Double>();
myList.add(new double [] {1,2,3});
myList.add(new double [] {4,5,6});
Would add two double arrays to myList. So: myList.get(0) would return: {1,2,3}
and myList.get(1) would return: {4,5,6}.
If you are trying to just create a list of doubles, and not a list of double arrays, you would do:
List<Double> myList = new ArrayList<Double>();
myList.add(1);
myList.add(2);
myList.add(3);
Now myList.get(0) will return 1 and myList.get(1) will return 2. Notice that to create a list of a primitive type, you need to specify the object version of that primitive type in the type parameter. I.e., you can't do: List<double>
This is because all type parameters just get converted to Object by the compiler.

Categories

Resources