Get int from Vector of Objects - java

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

Related

Why does this print exception?

String bob2 = "3";
System.out.println((int)bob2);
I'm unsure of why this causes an exception. Can anyone explain? Pretty sure because of the int on String type, but want to make sure.
Yes you are right its because of typecasting. If u need to convert String to int use below code
Integer.parseInt("3");
You are correct.
You can't just cast a string to an int.
You should convert it using Integer.parseInt()
Use this
Integer.valueOf("3");
or
Integer.parseInt("3");
In Java whenever you are trying to change type of an entity to another, both the types should have some relation. Like if you are trying to caste a sub class object to super class, it will work smoothly. But if you try to compare a Person object with a Lion object, that comparison is meaning less, the same is the logic in casting. We cannot cast a Person object to Lion object.
In your code bob is String type and you are trying to cast it to int and in Java both String and Integer is not having any relation. That's why Java is throwing Exception, Class Cast Exception I guess, this is raised when different types of objects are compared.
But the parseInt(String arg) method in Integer class gives an option to convert numeric String to Integer, given that the argument is a qualified Integer as per Java standards.
Example :-
String numericString = "1234";
int numberConverted = Integer.parseInt(numericString);
System.out.println(numberConverted);
You can also try these which will tell you the precautions before using this method
int numberConverted = Integer.parseInt("1234r");
int numberConverted = Integer.parseInt("1234.56");
int numberConverted = Integer.parseInt("11111111111111111111111111111");
You can't cast String to Integer. Change:
System.out.println((int)bob2);
to:
System.out.println(Integer.parseInt(bob2));
It will create an Integer value from the String provided with bob2 variable. You can also create a reference to int variable like this if you want to store primitive int instead of Integer:
int intBob2 = Integer.parseInt(bob2);

Trying to read Integer from JSON file in java

I am trying to read a JSON file to create a new Object. I can read all the Strings in it but i throws a ClassCastException when trying to read an int. Here is the JSON file.
{"id1" : "string1",
"id2": "string2",
"id3": 100.0
}
And here is the java code.
public static Aparelho novoAparelho(JSONObject obj) {
Aparelho ap = null;
String tipe = (String) obj.get("id1");
String name = (String) obj.get("id2");
if(tipe.equals("anyString")) {
int pot = (int) obj.get("id3");
ap = new SomeObject(name, pot);
}
return ap;
}
It throws.
Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer
Cast it to double first:
int pot = (int) (double) obj.get("id3");
ap = new SomeObject(name, pot);
Confusingly, there are three kinds of casts:
Those that convert values of primitives
Those that change the type of a reference
Those that box and unbox
In this case, you have an Object (which is actually a boxed Double), and you want a primitive int. You can't unbox and convert with the same cast, so we need two casts: first from Object to double (unboxing), and one from double to int (conversion).
Integers don't have decimal points.
You should be parsing for an int instead of casting as an int.
For example:
if (tipe.equals("anyString")) {
String pot = obj.get("id3");
int x = Integer.parseInt(pot);
ap = new SomeObject(name, x);
}
Since you know that the field is supposed to be an int, you can take advantage of the JSONObject api to handle the parsing for you:
if(tipe.equals("anyString")) {
int pot = obj.getInt("id3");
ap = new SomeObject(name, pot);
}
This is a bit more robust than the casting method -- if somebody changes the json that gets passed to you, the accepted answer might break.

Simplest way to retrieve an int from a mongo result?

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");

Looks like double type variables have no methods. Something wrong with Java or NetBeans?

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.

How convert an object to int

I want to convert an object to int type....
eg:
Object obj=........;
int count = Integer.parseInt((String) obj);
when i use above code ai got cast exception.
Anyone know how to cast object to int...?
Use obj.hashCode(), to get an int that represents the object. But what is your purpose? The code you posted does not work - you try to cast the object to a string rather than calling toString(), but even then, unless the toString representation of the object is itself an integer, calling Integer.parseInt on it will throw an exception.
So what are you aiming at?
If tableres is a Hashtable, the values are prolly Integer, not int.
In that case, try:
int i = ((Integer) tableres.get ("mCount")).intValue();
Good luck, - M.S.

Categories