Java Object Conversion to Integer and String wrapper - java

I have a java.lang.Object return type from a function. I want to verify whatever Object value returned is of numeric type (double or long or int or byte or Double or Long or Byte or Float or Double ....) and if it's true want to convert into a Integer wrapper reference type. Also if the Object instance holds a String value I want it to be stored in a String reference.

Have a Object return type from a function. I want to verify whatever Object value returned is of numeric type(double or long or int or byte or Double or Long or Byte or Float or Double ....)
if (obj instanceof Number)
...
if it's true want to convert into a Integer wrapper reference type
if ...
val = (Integer) ((Number) obj).intValue();
Also If the Object instance holds a String value i want it to be stored in a String reference.
...
else if (obj instanceof String)
val = obj;

A method that returns Object cannot return primitive types like double, long, or int.
You can check for the actual returned type using instanceof:
if (object instanceof Number){
// want to convert into a Integer wrapper reference type
object = ((Number)object).intValue(); // might lose precision
}
You can assign to a String variable by type-casting
if (object instanceof String){
stringVariable = (String)object;
}

Although you probably have a serious design problem, in order to achieve what you want you can use instanceof operator or getClass() method:
Object o = myFunction();
if(o instanceof Integer) { //or if o.getClass() == Integer.class if you want
only objects of that specific class, not the superclasses
Integer integer = (Integer) o;
int i = integer.intValue();
}
//do your job with the integer
if(o instanceof String)
//String job

You can do something like :
Object obj = getProcessedObject();
if(obj instanceof Number) {
// convert into a Integer wrapper reference type
Integer ref1 = ((Number)obj).intValue();
}
if(obj instanceof String) {
// process object for String
String ref = (String)obj;
}

Related

Is JsonElement integer or float?

Is it possible to determine whether a GSON JsonElement instance is an integer or is it a float?
I'm able to determine whether it's a number:
JsonElement value = ...
boolean isNumber = value.getAsJsonPrimitive().isNumber();
But how to determine if it's an integer or a float, so I can subsequently use the correct conversion method? Either
float f = value.getAsJsonPrimitive().getAsFloat();
or
int i = value.getAsJsonPrimitive().getAsInt();
Edit: The other question may answer why this may be not implemented in GSON, but this question definitely isn't its duplicate.
The only way I've found so far is using regex on a string:
if (value.getAsJsonPrimitive().isNumber()) {
String num = value.getAsString();
boolean isFloat = num.matches("[-+]?[0-9]*\\.[0-9]+");
if (isFloat)
System.out.println("FLOAT");
else
System.out.println("INTEGER");
}
This correctly determines 123 as integer, and both 123.45 and 123.0 as floats.
use something like, and so if return json object is an instance of float or integer you can then apply the required get:
JSONObject jObj = new JSONObject(jString);
Object aObj = jObj.get("a");
if(aObj instanceof Integer){
System.out.println(aObj);
}

How to input and return values from a method with generic types?

I'm trying to create the method deNull() to check input values. These input value might be String, int, double, Timestamp. Therefore, I create the method with generics types.
If the input value is null, then it will return "";
If the input value is not null, then return the original value.
My code is as below:
public static <T> T deNull(T value){
if(value == null ){
return "";
} else {
return value;
}
}
However, this method freaks out at line 3 and shows Type mismatch: Cannot convert from String to T.
How should I amend this method to make it run as expected ?
int and double can not be null anyway, that leaves Timestamp and String as the only two options.
In my opinion just write both methods without generics, not worth the hassle.
If you actually need it for more than two types, i would suggest changing the method to.
public static <T> T deNull(T value, T orElse){
if(value == null ){
return orElse;
} else {
return value;
}
}
String x = deNull( string, "");
Integer y = deNull( integer, 0);
(I would also suggest to change the method name to valueOrElse)
Since the return value is always a String type, decouple it from parameter type T.
public static <T> String deNull(T value) {
if (value == null) {
return "";
} else {
return value.toString();
}
}
If the 'T' is String your line 3 is valid else it is fail.
return "";
If the T is Integer string cannot cast to Integer
Integer a = 5;
String s = (String)a;//You cannot do like this

Store different datatype in same variable at runtime

I am new to android development. I am facing difficulties to store different types of data in same variable.
Example :
I want to store integer value 1 or String value "one" or double value 1.0 to my variable at run time when user press button. but Here I don't see any datatype for this. If I declare variable as String the I can't store integer value. If I declare variable as integer the I can't store String value.
Thanks in advance.
You can declare your variable of type Object
Object val;
val = Integer.valueOf(12);
val = Double.parseDouble("12")
val = String.valueOf("12");
Later to read the content of val you will have to test is type, or example using instanceof and cast it into the desired type...
Object val = Integer.valueOf(12);
if(val instanceof Integer){
Integer i = (Integer)val;
int iVal = i.intValue();
}else if(val instanceof Double){
//...
}else if (val instanceof String){
//...
}//...

Just need some enlightenment about .equals [duplicate]

This question already has answers here:
The equals() method in Java works unexpectedly on Long data type
(10 answers)
Closed 8 years ago.
Integer a = new Integer(1);
Integer b = new Integer(1);
Long c = new Long(1);
System.out.println(a.equals(b));
System.out.println(a.equals(c));
Question is why does a.equals(c) gives a false?
From Integer.equals():
The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.
c is not an Integer, so a.equals(c) returns false.
Because, you are using Integer class's equals method which does follows:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
The condition fails here if (obj instanceof Integer) as the obj i.e. c in your case is an instance of Long.
because both object are not of same Class one is Integer and other is Long, it will not only compare values when you say .equals()
The equals of Integer (and most classes) start with checking if the class of the parameter is equal to the objects own class. If not, equals will return false. This makes more sense if you would try to call equals between an integer and a string, they cannot be compared on values the same way as integer and long can. Therefore, all classes that are not integer and are calling equals on an integer object will return false.
if you look at the source of Integer.equales(Object obj) you'll see why:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
Long is not an instance of Integer.
In short: because c is not an Integer object. You're calling Integer#equals(Object) and passing a Long in as the parameter. The source code for Integer#equals(Object) is:
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}
Because obj is a Long and not an Integer, the if (obj instanceof Integer) check fails and the method then returns false.

How to check whether object Containing object collection

In Java i want to find whether object is a object collection??
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
I want to check varaible ob holds object collection??How can i do this??
You can use Java reflections, like this:
Class<?> clazz = ob.getClass();
boolean isArray = clazz.isArray();
check with instanceof operator.
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that >implements a particular interface.
reference
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
...
if(ob instanceof String[]){
String[] str = (String[])ob;
}else{...}
From your example, what you need to check is more precisely, Object Array instead of collection.
You can try something like
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
if (ob instanceof Object[]) {
// do something
}
First check is it an array with:
boolean isArray = ob.getClass().isArray();
or
if (ob instanceof Object[]) {
// ...
}
If not check is it an collection by checking with instanceof and java.util.Collection interface:
if (ob instanceof Collection) {
// ...
}

Categories