I'm pulling an int from a mongo cursor object like so:
DBObject mapObj = cursor.next();
int autostart = (int) (double) (Double) mapObj.get("autostart");
It seems strange that I have to triple cast to get it to an integer, is there a better way?
I think what you are really looking for is something like this:
DBObject mapObj = cursor.next();
int autostart = ((Number) mapObj.get("autostart")).intValue();
No conversion to a string and it is safe if the value gets converted to a Double or Long (with the potential loss of precision) from the original Integer value. Double, Long and Integer all extend Number.
HTH Rob
Also, you can do it this way:
int autostart = Integer.valueOf(mapObj.get("autostart").toString());
Regarding your last comment:
If you want double, use this:
int autostart = Double.valueOf(mapObj.get("autostart").toString());
But what is the sense in that? You could rather have :
double autostart = Double.valueOf(mapObj.get("autostart").toString());
Yep, you only need one cast.
double autostart = (Double) mapObj.get("autostart");
Related
I use a method to get Data from a database and store it in a vector. The method will always return a Vector of Objects where the Object datatype can be either a Date, a Double or a String. In my case, I know that I'm getting a Double, but I want to convert it to an int. is there any easier way than:
System.out.println((int)Double.parseDouble(vector1.get(1).toString()));
Other methods I tried that didn't work:
System.out.println((Integer)vector1.get(1)); // java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer
System.out.println((int)vector1.get(1));
Thanks in advance for any constructive response
Following this answer, we can transform the code into
Double d = vector1.get(1);
Integer i = d.intValue();
And I would assume here that if you have some array, maybe you want to transform all of the data there from Double into Integer
vector1.stream().mapToInt(n -> n.intValue()).mapToObj(Integer::new).collect(Collectors.toList());
or
vector1.stream().mapToInt(Double::intValue).mapToObj(Integer::new).collect(Collectors.toList());
You can use intValue() to get int value.
Double b = new Double((double)vector1.get(1));
int value = b.intValue();
You can use Math.round(double) to get the int value. As
Double d = Double.parseDouble(vector1.get(1));
int v = (int) Math.round(d);
In order to avoid possible loss of precision in Java operation on Double objects i.e.:
Double totalDouble = new Double(1590.0);
Double taxesDouble = new Double(141.11);
Double totalwithTaxes = Double.sum(totalDouble,taxesDouble);
//KO: 1731.1100000000001
System.out.println(totalwithTaxes); // 1731.1100000000001
I wrote this code, where totalDouble and taxesDouble could be also null:
Double totalDouble = myObject.getTotalDouble();
Double taxesDouble = myObject.getTaxesDouble();
BigDecimal totalBigDecimalNotNull = (totalDouble==null) ? BigDecimal.valueOf(0d):BigDecimal.valueOf(totalDouble);
BigDecimal taxesBigDecimalNotNull = (taxesDouble==null) ? BigDecimal.valueOf(0d):BigDecimal.valueOf(taxesDouble);
BigDecimal totalWithTaxesBigDecimal = totalBigDecimalNotNull.add(taxesBigDecimalNotNull);
System.out.println(totalWithTaxesBigDecimal);
Is there a better way (also with third part libraries i.e. guava, etc) to initialize BigDecimal in this cases (zero if Double is null and Double value otherwise)?
Not really. That is to say, you're still going to need to make a decision based on whether or not the value is null, but you can do it cleaner if you use the Optional pattern.
You can change your getTotalDouble and getTaxesDouble returns to Optional<Double> instead to mititgate having to do the ternary...
public Optional<Double> getTotalDouble() {
return Optional.ofNullable(totalDouble);
}
public Optional<Double> getTaxesDouble() {
return Optional.ofNullable(taxesDouble);
}
...then, you can use the conditional evaluation provided by Optional itself to evaluate and return a default value.
BigDecimal totalBigDecimalNotNull =
BigDecimal.valueOf(myObject.getTotalDouble().orElse(0d));
A simplification would be to return Optional<BigDecimal> instead, as opposed to transforming the value that you want in this fashion.
As an addendum, be careful when talking about precision. There is standing advice to use either int or long instead to ensure you don't lose any coin precision.
Whether you use Optional or not I recommend creating a static helper method so that you don't have to repeat yourself. e.g.:
public static BigDecimal bigDecimalValueOfOrZero(Double val) {
return val == null ? BigDecimal.ZERO : BigDecimal.valueOf(val);
}
I can implicitly conver int to long and long to Long. Why is it not possible to implicitly convert int to Long? Why can't Java do the implicit conversion on the last line of the example?
int i = 10; //OK
long primitiveLong = i; //OK
Long boxedLong = primitiveLong; //OK
boxedLong = i; //Type mismatch: cannot convert from int to Long
Long and Integer are objects. Boxing/unboxing only works with primitives.
Doing Long boxedLong = i is like Long boxedLong = new Integer(10), that's a no no !
Plus, remember that there is no inheritance between Long and Integer so even Integer i = new Long() is not valid
Boxing only works with primitives. That's why.
Try this: Long.valueOf(int);
Documentation
the biggest difference I see between long and Long in this context is that Long may be null. If there's a possibility you might have missing values the Long object will be helpful as the null can indicate missing values. If you're using primitives you'll have to use some special value to indicate missing, which is probably going to be a mess. Speed or size is not likely to be an issue unless you're planning on making an array of a million of these things and then serializing. (When to use Long vs long in java?)
In truth, there is no practical reason. Except that int is a primitive, long is a primitive, but Long is not.
I suggest you use Long.valueOf()
So like this:
Long longValue = Long.valueOf(InsertIntHere);
How do I save an Integer type (not int) into Database?
Using plain JDBC, I'd use the following:
Integer myInteger = ...;
PreparedStatement ps = ...;
if (myInteger == null) {
ps.setNull(1, Types.INTEGER);
} else {
ps.setInt(1, myInteger); // will be autounboxed
}
I think just use Integer is OK.Or use intValue() to convert it.
http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#setInt(int, int)
Depending on your database system (mysql, postgre, ...), the integer type will or won't exist in your database. It is then better to use java Integer functions to make an Integer from your database value, which will probably be int or even bigint, depending on what's needed.
As I said in my comment, something like Integer myinteger = new Integer(yourdatabasevalue) should work fine.
According to Oracle I should be able to apply methods like .intValue() and .compareTo() to doubles but when I write dbl.toString() in NetBeans, for example, the IDE tells me that doubles can't be dereferenced. I can't even cast them to Integers in the form (Integer) dbl!
I have JDK 1.6 and NetBeans 6.9.1. What's the problem here?
The methods you're mentioning are found on the Double class (and not in the double primitive type). It's always more efficient to use primitive types, but if you absolutely need those methods, create a new Double object like this:
double d = 10.0;
Double myDouble = new Double(d);
The problem is your understanding of objects vs. primitives.
More than anything else, you just need to recognize that the capitalized names are object classes that act like primitives, which are really only necessary when you need to send data from primitives into a method that only accepts objects. Your cast failed because you were trying to cast a primitive (double) to an object (Integer) instead of another primitive (int).
Here are some examples of working with primitives vs objects:
The Double class has a static method toString():
double d = 10.0;
// wrong
System.out.println(d.toString());
// instead do this
System.out.println(Double.toString(d));
Other methods can use operators directly rather than calling a method.
double a = 10.0, b = 5.0;
// wrong
if( a.compareTo(b) > 0 ) { /* ... */ }
// instead you can simply do this:
if( a >= b) { /* ... */ }
int a = 0;
double b = 10.0;
// wrong
a = b.intValue();
// perform the cast directly.
a = (int)b;
double is a primitive not an Object. As such it has no methods. Generally what you want to do is use the language like.
double d = 1.1;
System.out.println("d= "+d); // calls Double.toString(d) for you.
int i = (int) d; // more efficient than new Double(d).intValue();
if (d >= 1.0) // does a compare.
Perhaps if you say what you are trying to achieve we can point you to the Java code which will do that.
Every object has a toString method, so maybe your JDK is not configured properly in NetBeans.
You want (java.lang.)Double not the primitive double
Native types (int, float, double, etc) do not have methods.