using dataset.addSeries with a Long[] values [duplicate] - java

This question already has answers here:
How to convert array of floats to array of doubles in Java?
(3 answers)
Closed 9 years ago.
The arguments that dataset.addSeries takes are as follows (java.lang.Comparable key,
double[] values,
int bins,
double minimum,
double maximum)
Right now, I am trying to use a variable called Long[] v1 in the double[] values field and cannot figure out how to convert it.

From Jon Skeet's answer on How to convert array of floats to array of doubles in Java?, I quote:
Basically something has to do the conversion of each value. There
isn't an implicit conversion between the two array types because the
code used to handle them after JITting would be different - they have
a different element size, and the long would need a conversion whereas
the double wouldn't. Compare this to array covariance for reference
types, where no conversions are required when reading the data (the
bit pattern is the same for a String reference as an Object reference,
for example) and the element size is the same for all reference types.
In short, something will have to perform conversions in a loop. I
don't know of any built-in methods to do this. I'm sure they exist in
third party libraries somewhere, but unless you happen to be using one
of those libraries already, I'd just write your own method.
The following is an adapted implementation of Jon's answer to fit your question:
public static double[] convertLongsToDoubles(Long[] input)
{
if (input == null)
{
return null; // Or throw an exception - your choice
}
double[] output = new double[input.length];
for (int i = 0; i < input.length; i++)
{
output[i] = input[i];
}
return output;
}

You're going to have to do this yourself.
Write a method that does the conversion for you.
public static double[] convertFromLongToDouble(Long[] l) {
double[] doubleArray = new double[l.length];
// .. iterate through the Long array and populate to double array
return doubleArray;
}

Related

Getting exception while using the Generic Array? [duplicate]

This question already has answers here:
Explanation of ClassCastException in Java
(12 answers)
Closed 5 years ago.
I was using the following code to create a generic array of lists to mix up different types of lists:
List<Integer>[] intLists = (List<Integer>[])new List[] {Arrays.asList(1)};
List<? extends Object>[] objectList = intLists;
objectList[0] = Arrays.asList(1.01);
int n = objectList[0].get(0); // class cast exception!
But it gave me a cast exception.
How can I work around this?
I am not sure if this gives a compile error though it apparently is creating a raw array of lists and while storing it seems the compiler cannot detect that its an array of List (it cannot detect the type of list - so perhaps it just interprets it as a raw list) and hence does not throw an error and when you try and retrieve the element into an integer it fails while trying to cast a double into an int. This is not a correct usage.
I believe you can do (Integer) listArray[0].get(0) but it will cause precision loss post the floating point.
The type of objectList[0].get(0); is Double so you have to convert it to an int.
The following works:
int n = ((Double) objectList[0].get(0)).intValue();
But depending on you use case you code is not very good.
You're trying to store a double value in an integer variable. You can't do that. So just store it in a double instead:
List<Integer>[] intLists = (List<Integer>[])new List[] {Arrays.asList(1)};
List<? extends Object>[] objectList = intLists;
objectList[0] = Arrays.asList(1.01);
double n = (double) objectList[0].get(0); // Make it a double :)

Unknown n multidimension array in Java [duplicate]

This question already has answers here:
Java N-Dimensional Arrays
(3 answers)
Closed 5 years ago.
Is it possible to have an n dimensional array in Java without having to explicitly specify the number of dimensions?
I.e. if I wanted a 2D array of ints I'd do:
int[][] myArray = new int[a][b];
For the above I've had to specify that the myArray variable is of type int[][]. What I'm asking is whether there's the possibility to declare a variable that is an array of n dimensions without having to know n in advance.
I.e. If I had the variable test, test could be of type int[][] or int[][][] or int[][][][][][][][][][][] - you get the idea. I just want to define test without having to define the number of dimensions.
I'm sure the above kind of breaks the type system in Java so I'm open to any ideas as I think I'm approaching this the wrong way.
To give you a bit of context I've developed an algorithm to find an integer in a 2D array of integers that are sorted by both row and column in ascending order. I've noticed that it will work with any dimension array and would thus like to make it more generic. However, I don't fancy defining a function for every possible dimension of array to be passed as a parameter since the dimensions could (unlikely as it is) be anywhere from 1D to infinityD - hence the question.
This is also just for my own curiosity as to whether this can be done for any dimension array. I don't know whether this potentially can't be done using Java's built in facilities and I'd be better building my own class system to support multi-dimension arrays in this situation.
You can not define an array as unknown-dimensional. But you can make your own class like NDimensionalArray, that would wrap array of another NDimensionalArray instances, and implement getter like getValue(int indexes...), and dimension()
class NDimensionalArray {
NDimensionalArray[] arrays;
int value;
int getValue(int... indexes) {
if (indexes.length == 0) return value;
return arrays[indexes[0]].getValue(indexes[1],indexes[2],...,indexes[n-1]);
}
void setValue(int value, int... indexes) {
// implement simillary to getValue
}
int getDimension() {
if (arrays == 0 || arrays.length == 0) return 0;
return arrays[0].getDimension() + 1;
}
}
that's not a working class, but only an idea, creating the entire structure is on your own. You would need to implement all the index and null checks.

Array object and maximum

I know how to find minimum and maximum in an array. If a method lets say was called fMax():
public static double fMax(Object[] stuff)
The parameter is an array object how would I go about finding the max of this array? I cannot just do. Okay so how would I do this if I want the method to return a double and if the memory hasnt been allocated for the parameter named stuff then it will return the value NEGATIVE_INFINITY in the Double class, otherwise the return value will be the maximum value from the elements in the stuff array
Object max = stuff[0];
for (int i = 0; i < stuff.length; i++) {
if (data[i] > max) {
max = stuff[i];
}
}
To find the maximum of something, either
a) that something needs to implement the Comparable interface
b) you need to have some sort of explicit criteria for determining what maximum is, so you can put that in an instance of Comparator
Object itself isn't going to have anything useful for sorting. If you subclass object, you could sort based on the components of that object.
public class Example implements Comparable
{
int sortableValue = 0;
public Example (int value)
{
this.sortableValue = value;
}
public int compareTo(Example other)
{
return Integer.compare(this.sortableValue, other.sortableValue);
}
}
That's an object definition that has a natural sorting order. Java can look at that with any of the built in sorting algorithms and know the order they belong in.
If you don't provide java with a means of determining how an object has greater or lesser relative value compared to another object of the same type, it won't figure it out on its own.
Object is not comparable, you need a definite type if you want to compare values, sort or find something.
Streams are the most powerful, versatile tools for the job, this here will solve your problem if your want to find min/max of an array of Double :
Double[] arr = {1d, 2d, 3d, 4d};
Double min = Arrays.asList(arr).stream().parallel().min(Double::compare).get();
Double max = Arrays.asList(arr).stream().parallel().max(Double::compare).get();
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
Now, just compare the new primitive array that we made from the object. If you don't need the object after this, and you aren't planning on returning an array object, then make your original array null, to take up less memory.
Check this:
How to compare two object arrays in Java?

Making a variable length array of ints

I want to have a array of integers where the length is variable. The obvious choice is to use ArrayList but can I do this for primitive types such as
ArrayList<int> myArray=new ArrayList<int>();
I dont want to use
ArrayList<Integer>
because the Integer class is clumsy in terms of coding.
EDIT: From the answers below I think the solution is to write my own Integer class.
To answer the question below about "clumsy" let me give a specific, and I would of thought common use for integers namely using the last member of the array in any place you would want the integer. If I just call the array "name" then to get the actual integer that can be operated on I need
name.get(name.size()-1).intValue();
To me this seems like an awfully unwieldy expression for a simple integer - particularly if it appears in an expression twice. It also seems that (most of the) methods available for the Integer class are absolutely redundant. Take two examples
static int compare(int a, int b)
Quite unbelievably, according to the documentation, this method returns a-b!!
static Integer valueOf(int a)
returns an Integer instance of the integer a. Can someone give me a single example where
new Integer(a)
does not achieve exactly the same result?
Method 1: (not recommended)
You can do something like this, but this doubles the code and is not efficient:
int[] a;
//get size (from command line maybe ow whatever method you want)
You can set size 0 initially, and for ex. you are transferring values from arraylist so you will have to write:
while(itr.hasNext()){
size++;} //itr is an object of Iterator
int i=0;
a=new int[size];
// then loop again to store values
while(itr.hasNext()){
a[i]=itr.next();
i++;}
Method 2:
Or you may use ArrayList without making it clumsy as follows:
ArrayList al=new ArrayList();
then you may declare Integer objects as volatile and perform operations on them just as you do with the primitive types.
Method 3: (not recommended)
Or simply write:
ArrayList al=new ArrayList();//ignore the warning about <E>
int x=2;
al.add(2);
Method 4: (recommended)
If I were you I would use ArrayList<Integer>.
UPDATE: Another thing that might work is that you may initially create an ArrayList<Integer> and store values there and later convert it to int[]
This SO answer tells about the conversion. Quoted the code form there:
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
Hope this helps.
No it's not possible to use primitive types as generic type.
Well I would recommend you do use ArrayList and avoid primitive types in this case.
You can't change the size of an array once created. You have to allocate it bigger than you think you'll ever need
or
Accept the overhead of having to reallocate it to a new larger array and copy the data from the old to the new:
System.arraycopy(oldItems, 0, newItems, 0, 10);
But Much simpler to go with ArrayList.

How to set to int value null? Java Android [duplicate]

This question already has answers here:
What is the difference between an int and an Integer in Java and C#?
(26 answers)
Closed 9 years ago.
which is the best way to set already defined int to null?
private int xy(){
int x = 5;
x = null; //-this is ERROR
return x;
}
so i choose this
private int xy(){
Integer x = 5;
x = null; //-this is OK
return (int)x;
}
Then i need something like :
if(xy() == null){
// do something
}
And my second question can i safely cast Integer to int?
Thanks for any response.
You can't. int is a primitive value type - there's no such concept as a null value for int.
You can use null with Integer because that's a class instead of a primitive value.
It's not really clear what your method is trying to achieve, but you simply can't represent null as an int.
In this case, I would avoid using null all together.
Just use -1 as your null
If you need -1 to be an acceptable (not null) value, then use a float instead. Since all your real answers are going to be integers, make your null 0.1
Or, find a value that the x will never be, like Integer.MAX_VALUE or something.
Only objects can be null. Primitives (like int) can't.
can i safely cast Integer to int?
You don't need a cast, you can rely on auto-unboxing. However it may throw a NullPointerException:
Integer i = 5;
int j = i; //ok
Integer k = null;
int n = k; //Exception
Your method compiles, but will throw NullPointerException when trying to unbox the Integer...
The choice between Integer and int depends on what you are trying to achieve. Do you really need an extra state indicating "no value"? If this is a legitimate state, use Integer. Otherwise use int.

Categories