Getting exception while using the Generic Array? [duplicate] - java

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 :)

Related

What is the formulation for Java Array class names? [duplicate]

This question already has answers here:
What is this: [Ljava.lang.Object;?
(2 answers)
Closed 2 years ago.
I have a need to create the class name of an array in Java. I notice when using reflection to look at class names an array has a certain pattern:
For example for an array of array of com.foo.Thing
[[Lcom.foo.Thing;
What is the formula used to create this class name? I presume other letters besides 'L' mean different things. Are there libraries that help with this?
One letter for each primitive, one symbol for arrays, and one letter for reference:
I = int
J = long
D = double
F = float
Z = boolean
C = char
B = byte
S = short
Lcom/foo/Thing; = reference 'com.foo.Thing'
[ = array of whatever is next (so, [[I is an int[][]).
This is VM-speak for type signatures. For example, the signature of:
public boolean[] foo(String[] args, int count) { ... }
is: ([Ljava/lang/String;I)[Z.
It is for machines and not humans; it is easy to parse (you just move forward, no need to look-ahead).
This is not the 'class name' of a thing; the usual name for this construct is 'vm name'. Note that generics just disappear from these; the VM name of List<String> is Ljava/util/List;. It's why you can't override methods if the two methods end up with the same name, param types, and return type if you remove all generics.

Incompatible types java.util.List double

How to resolve this issue?
public List<Double> getIntermediateGrade(){
List<Evaluation> evaluationList = evaluationRepository.getAll();
List<Double> evaluationGrades = new ArrayList<Double>();
for (Evaluation evaluation : evaluationList){
evaluationGrades = evaluation.getIntermidiateGrade();//error here
}
return evaluationGrades;
}
The error is:
Incompatible types: java.util.List <java.util.Double> , Double
How to change the line inside the for in order to work?
Probably a careless error as you're trying to equate a List with a Double. Instead you want to add to the list, so change
evaluationGrades = evaluation.getIntermidiateGrade();
to
evaluationGrades.add(evaluation.getIntermidiateGrade());
Lesson: the error messages don't lie and will often tell you exactly what's wrong. Look closely at the message and the line and look for your mistake.

BigInteger, Integer too large [duplicate]

This question already has answers here:
Error assigning to an an element in an array of BigInteger
(4 answers)
Closed 7 years ago.
Trying to use BigInteger first time, and this is my code:
public class Factx
{
public static void main(String[] args)
{
BigInteger[] asd = new BigInteger[10];
asd[0] = 123456458979851322316546445665;
System.out.println(asd[0]);
}
}
Compiling this, gives an error Integer number too large
I also tried changing,
asd[0] = new BigInteger(123456458979851322316546445665);
referred some other questions as well, didn't do much help, am I missing something? Whats the best fix? Thanks,
asd[0] = 123456458979851322316546445665; doesn't work for two reasons :
You can't assign a primitive value to a variable whose type is a reference type (unless that reference type is the wrapper class of that primitive type, like Integer is the wrapper of int).
123456458979851322316546445665 is too large for an int literal (and even if you add L suffix, it will still be too large for a long literal). This also explains why asd[0] = new BigInteger(123456458979851322316546445665); doesn't work.
Instead, use the BigInteger constructor that takes a String :
BigInteger[] asd = new BigInteger[10];
asd[0] = new BigInteger("123456458979851322316546445665");
System.out.println(asd[0]);
Output:
123456458979851322316546445665
Create BigInteger via
asd[0] = new BigInteger("123456458979851322316546445665");
BigInteger doesn't accept explicit cast from integer to BigInteger, only via constructors.

Java type casting generics list of list of child to list of list of parent [duplicate]

This question already has answers here:
How do you cast a List of supertypes to a List of subtypes?
(20 answers)
Closed 8 years ago.
I have a class like ChildData1 which extends from Data.
How can I convert a List<List<ChildData1>> to a List<List<Data>> ?
Under the rules of generics you can do the following assignment without the cast:
List<List<ChildData>> subClassList = ...
List<? extends List<? extends Data>> superClassList = subClassList;
Traverse the elements of list and TYPECAST it.
Imagine if you could do this:
List<List<ChildData1>> foo = getListOfListOfChildData();
List<List<Data>> bar = foo; // there's your cast
ChildData2 childData2 = getSomeOtherChildData();
bar.get(0).add(childData2); // now you've added ChildData2
for (ChildData1 childData1 : foo.get(0)) {
// Whoops! Suddenly you've got a ChildData2 in your ChildData1.
}
These types are not naturally compatible, and not easily converted to one another without some kind of #SuppressWarnings.
If Data is a parent no need to explicitly typecast it.
List<List<Data>>> data = somemethod();
List<List<ChildData>>> somemethod(){};

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

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;
}

Categories