Safely casting long to int in Java - java

What's the most idiomatic way in Java to verify that a cast from long to int does not lose any information?
This is my current implementation:
public static int safeLongToInt(long l) {
int i = (int)l;
if ((long)i != l) {
throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
}
return i;
}

A method was added in Java 8:
import static java.lang.Math.toIntExact;
long foo = 10L;
int bar = toIntExact(foo);
Will throw an ArithmeticException in case of overflow.
See: Math.toIntExact(long)
Several other overflow safe methods have been added to Java 8. They end with exact.
Examples:
Math.incrementExact(long)
Math.subtractExact(long, long)
Math.decrementExact(long)
Math.negateExact(long),
Math.subtractExact(int, int)

I think I'd do it as simply as:
public static int safeLongToInt(long l) {
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
throw new IllegalArgumentException
(l + " cannot be cast to int without changing its value.");
}
return (int) l;
}
I think that expresses the intent more clearly than the repeated casting... but it's somewhat subjective.
Note of potential interest - in C# it would just be:
return checked ((int) l);

With Google Guava's Ints class, your method can be changed to:
public static int safeLongToInt(long l) {
return Ints.checkedCast(l);
}
From the linked docs:
checkedCast
public static int checkedCast(long value)
Returns the int value that is equal to value, if possible.
Parameters:
value - any value in the range of the int type
Returns:
the int value that equals value
Throws:
IllegalArgumentException - if value is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE
Incidentally, you don't need the safeLongToInt wrapper, unless you want to leave it in place for changing out the functionality without extensive refactoring of course.

With BigDecimal:
long aLong = ...;
int anInt = new BigDecimal(aLong).intValueExact(); // throws ArithmeticException
// if outside bounds

here is a solution, in case you don't care about value in case it is bigger then needed ;)
public static int safeLongToInt(long l) {
return (int) Math.max(Math.min(Integer.MAX_VALUE, l), Integer.MIN_VALUE);
}

DONT: This is not a solution!
My first approach was:
public int longToInt(long theLongOne) {
return Long.valueOf(theLongOne).intValue();
}
But that merely just casts the long to an int, potentially creating new Long instances or retrieving them from the Long pool.
The drawbacks
Long.valueOf creates a new Long instance if the number is not within Long's pool range [-128, 127].
The intValue implementation does nothing more than:
return (int)value;
So this can be considered even worse than just casting the long to int.

I claim that the obvious way to see whether casting a value changed the value would be to cast and check the result. I would, however, remove the unnecessary cast when comparing. I'm also not too keen on one letter variable names (exception x and y, but not when they mean row and column (sometimes respectively)).
public static int intValue(long value) {
int valueInt = (int)value;
if (valueInt != value) {
throw new IllegalArgumentException(
"The long value "+value+" is not within range of the int type"
);
}
return valueInt;
}
However, really I would want to avoid this conversion if at all possible. Obviously sometimes it's not possible, but in those cases IllegalArgumentException is almost certainly the wrong exception to be throwing as far as client code is concerned.

Java integer types are represented as signed. With an input between 231 and 232 (or -231 and -232) the cast would succeed but your test would fail.
What to check for is whether all of the high bits of the long are all the same:
public static final long LONG_HIGH_BITS = 0xFFFFFFFF80000000L;
public static int safeLongToInt(long l) {
if ((l & LONG_HIGH_BITS) == 0 || (l & LONG_HIGH_BITS) == LONG_HIGH_BITS) {
return (int) l;
} else {
throw new IllegalArgumentException("...");
}
}

(int) (longType + 0)
but Long can not exceed the maximum :)

One other solution can be:
public int longToInt(Long longVariable)
{
try {
return Integer.valueOf(longVariable.toString());
} catch(IllegalArgumentException e) {
Log.e(e.printstackstrace());
}
}
I have tried this for cases where the client is doing a POST and the server DB understands only Integers while the client has a Long.

Related

How do I return a Number object of the same concrete type as one passed in?

I have the following incomplete class. It implements a method that takes any Number object as a parameter and constrains it to a limit stored in a long and then returns the original value or the constrained value. However, the returned constrained value must be of the same concrete type as the input parameter.
public class Max implements Constraint {
long max;
public Number constrain(Number n) {
if (n.longValue() <= max) {
return n;
}
// return a number of the type passed in with value max
}
}
There are other questions about creating an object of the same type as another, but the answers assume a no-arg constructor is available and this is not the case for the numeric types.
I have played with:
n.getClass().getConstructor(new Class<?>[] { n.getClass() }).newInstance(max);
but I still have issues about passing in the right parameter even here. I am back to square one. In any case, it isn't very elegant.
I know I can do it with a lot of if statements, but I am looking for something smarter.
Because the constuctor of SubClasses of Number takes primitives as parameter, you cannot look for the constructore that has the Wrapper Class as parameter
The constructor that they all have, is the String one
long max;
public Number constrain(Number n) {
if (n.longValue() <= max)
try{
return n.getClass()
.getConstructor(String.class)
.newInstance(String.valueOf(max));
}catch(Exception ex){ex.printStackTrace();}
return n;
}
public static void main(String[]args){
Max m = new Max();
m.max = 10;
System.out.println(m.constrain(new Double(25)).getClass()); // class java.lang.Double
System.out.println(m.constrain((int) 18).getClass()); // class java.lang.Integer
}
Working DEMO
with Java 5 or hogher you can use a generic in your methods like this
package test;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Assert;
public class Max {
Number max;
public <T extends Number> T constrain(T n) {
if (n.floatValue() <= max.floatValue()) {
return n;
} else {
return castTo(max, n.getClass());
}
}
#SuppressWarnings("unchecked")
private <T extends Number> T castTo(Number max2, Class<? extends Number> class1) {
if (class1.equals(AtomicInteger.class)) {
return (T) new AtomicInteger(max2.intValue());
} else if (class1.equals(AtomicLong.class)) {
return (T) new AtomicLong(max2.longValue());
// these case are dangerous to handle
} else if (class1.equals(BigDecimal.class)) {
return (T) BigDecimal.valueOf(max2.doubleValue());
} else if (class1.equals(BigInteger.class)) {
return (T) BigInteger.valueOf(max2.longValue());
// Std Case
} else if (class1.equals(Byte.class)) {
return (T) (Byte) max2.byteValue();
} else if (class1.equals(Double.class)) {
return (T) (Double) max2.doubleValue();
} else if (class1.equals(Float.class)) {
return (T) (Float) max2.floatValue();
} else if (class1.equals(Integer.class)) {
return (T) (Integer) max2.intValue();
} else if (class1.equals(Long.class)) {
return (T) (Long) max2.longValue();
} else if (class1.equals(Short.class)) {
return (T) (Short) max2.shortValue();
} else {
throw new IllegalArgumentException("Can't handle this kind of Number : " + class1.getName());
}
}
public static void main(String[] args) {
Max max = new Max();
max.max = 32;
Integer constrain = max.constrain(33);
Assert.assertEquals(Integer.class, constrain.getClass());
Assert.assertEquals(max.max, constrain);
Double constrain2 = max.constrain(33d);
Assert.assertEquals(Double.class, constrain2.getClass());
Assert.assertEquals(max.max.doubleValue(), constrain2, 0);
Float constrain3 = max.constrain(33f);
Assert.assertEquals(Float.class, constrain3.getClass());
Assert.assertEquals(max.max.floatValue(), constrain3, 0);
Short constrain4 = max.constrain((short) 33);
Assert.assertEquals(Short.class, constrain4.getClass());
Assert.assertEquals(max.max.shortValue(), constrain4, 0);
Byte constrain5 = max.constrain((byte) 33);
Assert.assertEquals(Byte.class, constrain5.getClass());
Assert.assertEquals(max.max.byteValue(), constrain5, 0);
Long constrain6 = max.constrain(33l);
Assert.assertEquals(Long.class, constrain6.getClass());
Assert.assertEquals(max.max.longValue(), constrain6, 0);
BigDecimal constrain7 = max.constrain(BigDecimal.valueOf(33));
Assert.assertEquals(BigDecimal.class, constrain7.getClass());
BigInteger constrain8 = max.constrain(BigInteger.valueOf(33));
Assert.assertEquals(BigInteger.class, constrain8.getClass());
AtomicInteger constrain9 = max.constrain(new AtomicInteger(33));
Assert.assertEquals(AtomicInteger.class, constrain9.getClass());
AtomicLong constrain10 = max.constrain(new AtomicLong(33));
Assert.assertEquals(AtomicLong.class, constrain10.getClass());
}
}
but inside your code to construct all child of number there no common constructor the safest way is to reduce the case you want handle here i didn't handle all Striped64 children
I discovered:
import org.apache.commons.beanutils.ConvertUtils;
...
return (Number)ConvertUtils.convert(max, n.getClass());
I haven't looked at the source, but I doubt it is very clever inside. I believe it just hosts a collection of type converters.
So this is an alternative - not better than the other answers, but at least it is concise.
Edit - v3 - without String.
If you only talk about members of Numbers that allows primitive type as the input of constructor like Float/Double/Integer/Long/..., the following could work:
//Number n is valid someInput;
//Note this only works for Classes that take a single numeric value as input
Class type = (Class) n.getClass().getDeclaredField("TYPE").get(n);
return n.getClass().getConstructor(type).newInstance(max)
Things like BigInteger will not work with this one.
Edit - v2
It seems like, for primitive types n, if the "Number n" is replaced by different signatures and by using Integer.TYPE (or Float.TYPE and etc.) you might pass in the 'int' as parameters of getConstructor. You may use n.TYPE here (but as a reminder TYPE is the class member, and it may pop some warning).
n.getClass().getConstructor(n.TYPE).newInstance(max);
Still, as #azro pointed out: if you insist not using string and want it smart, you still need branches and it could be nastier: you need to consider all subclasses of Number, including BigInteger.
True, casting it to string is nasty, but otherwise, you may need to wrap each subclass of Number with an extra class that allows the non-primitive type as args of the constructor. I barely think if-statements is nastier.
Original Answer
I am not very familiar with Reflection.
But a major problem here is the constructor of Numbers are either String or primitive types like 'int', and you cannot really utilize 'int' as the input of getConstructor.
at least, the following may work.
//assume n is some Number object.
n.getClass().getConstructor(String.class).newInstance(max.toString());
This works as classes like Float/Integer/BigInt.../ have constructors that take String as the input.

For which double value is a comparison with itself the fastest?

Just to put my question in context: I have a class that sorts a list in its constructor, based on some calculated score per element. Now I want to extend my code to a version of the class that does not sort the list. The easiest (but obviously not clean, I'm fully aware, but time is pressing and I don't have time to refactor my code at the moment) solution would be to just use a score calculator that assigns the same score to every element.
Which double value should I pick? I was personally thinking +Infinity or -Infinity since I assume these have a special representation, meaning they can be compared fast. Is this a correct assumption? I do not know enough about the low level implementation of java to figure out if I am correct.
In general avoid 0.0, -0.0 and NaN. Any other number would be fine. You may look into Double.compare implementation to see that they are handled specially:
if (d1 < d2)
return -1; // Neither val is NaN, thisVal is smaller
if (d1 > d2)
return 1; // Neither val is NaN, thisVal is larger
// Cannot use doubleToRawLongBits because of possibility of NaNs.
long thisBits = Double.doubleToLongBits(d1);
long anotherBits = Double.doubleToLongBits(d2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
However that depends on how your sorting comparator is implemented. If you don't use Double.compare, then probably it doesn't matter.
Note that except these special cases with 0.0/-0.0/NaN double numbers comparison is wired inside the CPU and really fast, thus you are unlikely to get any significant comparison overhead compared to the other code you already have.
No sure how this would fit in but have you considered writing your own?
It just seems a little concerning that you are looking for an object with specific performance characteristics that are unlikely to consistently appear in a general implementation. Even if you find a perfect candidate by experiment or even from source code you could not guarantee the contract.
static class ConstDouble extends Number implements Comparable<Number> {
private final Double d;
private final int intValue;
private final long longValue;
private final float floatValue;
public ConstDouble(Double d) {
this.d = d;
this.intValue = d.intValue();
this.longValue = d.longValue();
this.floatValue = d.floatValue();
}
public ConstDouble(long i) {
this((double) i);
}
// Implement Number
#Override
public int intValue() {
return intValue;
}
#Override
public long longValue() {
return longValue;
}
#Override
public float floatValue() {
return floatValue;
}
#Override
public double doubleValue() {
return d;
}
// Implement Comparable<Number> fast.
#Override
public int compareTo(Number o) {
// Core requirement - comparing with myself will always be fastest.
if (o == this) {
return 0;
}
return Double.compare(d, o.doubleValue());
}
}
// Special constant to use appropriately.
public static final ConstDouble ZERO = new ConstDouble(0);
public void test() {
// Will use ordinary compare.
int d1 = new ConstDouble(0).compareTo(new Double(0));
// Will use fast compare.
int d2 = ZERO.compareTo(new Double(0));
// Guaranteed to return 0 in the shortest time.
int d3 = ZERO.compareTo(ZERO);
}
Obviously you would need to use Comparable<Number> rather than Double in your collections but that may not be a bad thing. You could probably craft a mechanism to ensure that the fast-track compare is always used in preference (depends on your usage).

Can try catch be used for code optimization?

Lets say I have following class:
public class RectangularPrism{
public Integer width;
public Integer height;
public Integer depth;
//setters and getters
}
I use it for calculate sum of volume of all prisms. I have two methods to calculate this. Which one is better?
This one use conditional operator.
public Integer volumeSum(List<RectangularPrism> prismList){
Integer sum = 0;
for(RectangularPrism prism: prismList){
Integer width = prism.getWidth() == null ? 0 : prism.getWidth();
Integer height = prism.getHeight() == null ? 0 : prism.getHeight();
Integer depth = prism.getDepth() == null ? 0 : prism.getDepth();
sum += width * height * depth;
}
return sum;
}
This one use try catch block
public Integer volumeSum(List<RectangularPrism> prismList){
Integer sum;
for(RectangularPrism prism: prismList){
try {
Integer width = prism.getWidth();
Integer height = prism.getHeight();
Integer depth = prism.getDepth();
sum += width * height * depth;
}catch( NullPointerException e){}
}
return sum;
}
Which one would be better If my class would have 100 or more fields which determine result?
Is it fine to use try catch to handle null values?
This is a bad idea on every level.
try-catch is actually slower (if there really is an exception thrown)
You're using exceptions in a non-exceptional case (i.e. normal control flow), which is conceptually wrong.
If anything else in the try-catch block throws a legitimate NPE, you have no way of telling what happened. (Imagine the case when prism itself is null for example.)
It is very difficult to figure out from the code alone what your intent was. Using the ?: operator to check for nulls is a well-established pattern that everyone will recognise.
An empty catch block is a big no-no, and probably the most reliable method of generating bugs that will take ages to track down.
In this case the two snippets aren't even equivalent, as in the "exception-driven" one a null value will mean the rest of the try block will be skipped. Of course the sum will still be correct but that's just a coincidence.
If you really want to improve performance, don't use Integer and other wrapping classes for simple calculations, use the corresponding primitive (int in this case) instead. The added bonus of this is that you suddenly won't have to worry about nulls any more because primitive values can never be null.
So to sum it up: never ever do this.
Seriously, don't. Every time you do it, a cute little kitten dies.
You should never use try-catch to handle the control flow of your program.
Always use the established methods, in this case, check for null as you do in your first code sample.
I know this will not answer the question (Can try .. catch be used for code optimization), but I think you should rarely bother with null values: you should enforce the (width, height, depth) to be non null if they are intrinsic property of your object.
I mean, you are building a RectangularPrism: width, height, and depth define this object. You can't have null in there because otherwise it would not be a rectangular prism.
In that case, I would rather do that:
public class RectangularPrism {
private final Integer width;
private final Integer height;
private final Integer depth;
public RectangularPrism(Integer width, Integer height, Integer depth) {
this.width = Objects.requireNonNull(width, "width");
this.height = Objects.requireNonNull(height, "height");
this.depth = Objects.requireNonNull(depth, "depth");
}
// getters
}
Or with setter:
public class RectangularPrism {
public Integer width;
public Integer height;
public Integer depth;
public void setWidth(Integer width) {
this.width = Objects.requireNonNull(width, "width");
}
}
You don't have to handle null because the JVM will throw a NullPointerException, but only because the object was not fully/correctly initialized, not because you did not handle a null value that should not be there. This is a normal behavior like throwing an IllegalStateException because the object is in a state it should not be (here: because you have null values).
And to be complete, you would have a better implementation if the volume computation were an operation on RectangularPrism rather than an external operation.
This way would be more correct:
public class RectangularPrism {
private final Integer width;
private final Integer height;
private final Integer depth;
public RectangularPrism(Integer width, Integer height, Integer depth) {
this.width = Objects.requireNonNull(width, "width");
this.height = Objects.requireNonNull(height, "height");
this.depth = Objects.requireNonNull(depth, "depth");
}
public Integer computeVolume() {
return width * height * depth; // can't be null.
}
}
Then (I used int there, because there is a sum, I won't comment the use of primitive over wrapper class):
public Integer volumeSum(List<RectangularPrism> prismList) {
int initial = 0;
for (RectangularPrism p : prismList)
initial += p.computeVolume();
return initial;
}
And last but not least, exception handling is slower, but exception handling in a loop is way slower.

Using Generics of Subclasses of Number to Create a Rollover Counter

I'm trying to create a counter that will rollover whenever it reaches a preset ceiling and resets back to its floor value upon reaching said ceiling. I have implemented the class and it works just fine. However, on my way to my solution, I wanted to experiment with Java Generics. I want to try and extend my counter so that it doesn't only use integers, but instead can use any type of number. I know that counters typically call for just the use of integers anyway, but I wanted to see if it could be done.
I figured that the code would be similar to below. However, java.lang.Number doesn't have a "generic" way of getting/setting its value. Do I need to create my own number class to enable this? Also, I know that if I do get this working, I need to alter my equals checks so that they have an error threshold for floating point values, this is more or less a modified version of my int counter with what I figured would work for generics.
Edit:
It's been suggested that I take a mapping approach where I store an integer counter and keep a increment value so that when I want to spit out a number, I just multiply my current count by the increment value. However, I don't believe this will fill my exact needs because I don't want to necessarily increment by the same amount every time. The main focus of this counter is more of a way to have a fixed range number that, when added to or subtracted from, knows how to handle wrapping back around.
I guess the best way to describe it (although probably improperly) would be like an Integer that automatically handles over/underflow.
package com.math;
public class GenericRolloverCounter<T extends Number> {
private T value;
private T lowValue;
private T highValue;
public GenericRolloverCounter(T l_startValue, T l_highValue) {
this.lowValue = l_startValue;
this.highValue = l_highValue;
this.value = l_startValue;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
public void increment(T valToIncrementBy) {
this.value += valToIncrementBy;
if (this.value > this.highValue) {
this.value = (this.lowValue + (this.value - (this.highValue + 1)));
}
}
public void increment() {
this.increment(1);
}
public void decrement(T valToDecrementBy) {
this.value -= valToDecrementBy;
if (this.value < this.lowValue) {
this.value = ((this.value + this.highValue + 1) - this.lowValue);
}
}
public void decrement() {
this.decrement(1);
}
#Override
public String toString() {
return Integer.toString(this.value);
}
}
You might want to also specify an amount by which to count. Default value would be 1.
You can get around some of this by using the Number method .doubleValue() and doing double arithmetic.
Here is one of the methods converted to use this idea.
public void decrement(double valToDecrementBy) {
double work = this.value.doubleValue();
work -= valToDecrementBy;
// should use some value related to incrementing amount
if ((this.value.doubleValue() - this.lowValue.doubleValue()) < 0.1D) {
work = ((this.value.doubleValue() + this.highValue.doubleValue() + 1) - this.lowValue.doubleValue());
}
// ... no way to put it back
}
But, there is still no way to put the value back that's clean and easy. Since 'Number' only has a few commonly used non-abstract subclasses, you could do some ugly instanceof stuff to store the value back. It would look something like this:
if (theValue instanceof Double) { // depends on it having a non-null value prior
theValue = (T)(new Double(work));
}
Or you could convert the starting values to double when you start and just work with doubles.
private double value;
private double lowValue;
private double highValue;
public GenericRolloverCounter(T l_startValue, T l_highValue) {
this.lowValue = l_startValue.doubleValue();
this.highValue = l_highValue.doubleValue();
this.value = l_startValue.doubleValue();
}
That does introduce the issues of incrementing floating point values and the rounding/evaluation problem there.
Oh ... and your toString() should be:
return value.toString();
To use the native toString() method on the T class.
#Crusher's comments suggest another way to do it. Map everything to 'int' and keep a multiplier. Here's some bits of code to show what I mean. (Thanks Crusher)
private int value;
private int lowValue;
private int highValue;
private double incr;
public GenericRolloverCounter(T l_startValue, T l_highValue, T incrementAmount) {
double incr = incrementAmount.doubleValue();
this.lowValue = Math.round(l_startValue.doubleValue() / incr);
this.highValue = Math.round(l_highValue.doubleValue() / incr);
this.value = Math.round(l_startValue.doubleValue() / incr);
}
public void increment(int valToIncrementBy) {
this.value += valToIncrementBy;
if (this.value > this.highValue) {
this.value = (this.lowValue + (this.value - (this.highValue + 1)));
}
}
#Override
public String toString() {
return String.valueOf(incr * this.value);
}

What is the correct way to return a substring(n, m) within a method statement in Java?

I am going through previous exam questions and my question is what is the correct way or ways to determine a String length and return it.
If the String is less than 5 characters in length then I can return it the following way:
public static String first5(String s){
if(s.length() < 5)
return s;
}
If the String is greater than 5 characters though, it can be returned in the following way:
public static String first5(String s){
return s.substring(0, 4);
}
What I must note is that when I answered this type of question before in an in class test, my lecturer stressed that I should not really use 'magic numbers'?
I am not sure what he actually meant by that though.
Is there a better way to return this type of method at all?
I am still learning Java so please forgive any errors in my syntax.
Many thanks.
This should be your method first5:
public static String first5(String s){
return s.length() < 5? s : s.substring(0, 5);
}
There are no magic numbers here, but maybe the teacher meant the number 5 was a magic number and wanted you to generalize the function:
public static String firstN(String s, int n){
return s.length() < n? s : s.substring(0, n);
}
Note that there's no great shame in using an if statement:
String r = null;
if (s.length() < 5) {
r = s;
}
else {
r = s.substring(0,5);
}
return r;
The logic is clearer than if you use ?:. The advantage of the latter is that it occupies less screen real-estate, so you can get more of a large function onto a screen -- valuable if you have a large function, but counter-productive if not.
Essentially if the requirements ever change, you can easily change the value in one location; thus, it will be changed everywhere it's referenced. You won't have to worry about any fragments of the old requirements floating around in the code. This is generally a good rule to follow with a large chunk of code.
public class solution {
static final int VAR1 = 0;
static final int VAR2 = 4;
static final int VAR3 = 5;
public static String first5(String s){
if(s.length() < VAR3) {
return s;
} else {
return s.substring(VAR1, VAR2);
}
}
}
Of course the variable names will have to be named something meaningful to the class/application itself.
Is the number 5 is in your question? If not get the number as input argument with the string input.

Categories