BigInteger, Integer too large [duplicate] - java

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.

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.

what's the differences between using <> and not using it in java? [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 4 years ago.
I have a piece of code like this:
#RequestMapping(value = "/find/{id}")
#GetMapping
public ResponseEntity<QuestionModel> find(#PathVariable("id") Long id) {
Question question = questionService.find(id);
QuestionModel questionModel = new QuestionModel(question);
**return new ResponseEntity<>(questionModel, HttpStatus.OK);**
}
I wanna know that what's differences between that & this:
#RequestMapping(value = "/find/{id}")
#GetMapping
public ResponseEntity<QuestionModel> find(#PathVariable("id") Long id) {
Question question = questionService.find(id);
QuestionModel questionModel = new QuestionModel(question);
**return new ResponseEntity(questionModel, HttpStatus.OK);**
}
If you don't use any <...> you will use raw-types. You should never use raw-types, generics are way safer to use and prevent way more bugs due to increased compiler knowledge. Java only still supports it for backwards compatibility reasons < Java 5. See What is a raw type and why shouldn't we use it?
Using <> (diamond operator) instead of <Foo> (writing it out) is just syntactic sugar for convenience. The compiler replaces the diamond operator with the fully-written out type (same for var in Java 10). See What is the point of the diamond operator in Java 7?
// Are the same
List<Integer> values = new ArrayList<Integer>();
List<Integer> values = new ArrayList<>();
// Raw types, don't use if > Java 5
List values = new ArrayList();
// Assigning a raw-type to a generic variable, mixing both, don't use
List<Integer> values = new ArrayList();

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

Can the integer once converted to String using toString() method be reconverted back to Integer? [duplicate]

This question already has answers here:
How do I convert a String to an int in Java?
(47 answers)
Closed 7 years ago.
public class ArrayManipulations {
public static void main(String[] args) {
String name = num.toString();
System.out.println(name); // want to convert this back to int
System.out.println(num.getClass().getName() + '#' + Integer.toHexString(num.hashCode()));
}
}
Now i want to convert the name back to integer.
is it possible???
Yes.
int i = Integer.parseInt(name);
Yes you can
Return an Object Integer :
Integer var = Integer.valueOf("0");
This method returns the relevant Number Object holding the
value of the argument passed. The argument can be a primitive data
type, String, etc.
Return a primitive int :
int var = Integer.parseInt("0");
This method is used to get the primitive data type of a certain
String. parseXxx() is a static method and can have one argument or
two.
The Integer class provides the following method for this task:
Integer.parseInt(String s);
Yes.
Integer.parseInt(Integer.toString(3));
should do the trick.
More in the Java Documentation.
If you want to convert String to int, you use:
int intNum = Integer.parseInt(name); //name is variable that you want to change back to int

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