Java Cast from Object to long to String - java

Here's the situation, I have an Object in a Map which I explicitly know to contain an instance of Long and I need to turn that value into a string but keep getting incompatible type errors. Here's what my code looks like:
Map<String, Object> map = ...;
Object obj = new Long(31415L);
String str = Long.valueOf((long)map.get("id")); //Problem line
This gives:
Inconvertible types.
Found : java.lang.Object
Required: long
Any suggestions as to how to get around this?

You can just do
String str = map.get("id").toString();

Use, for instance:
String.valueOf(map.get("id"))
The problem is that you try and cast an object to a primitive type. That cannot work.
But since the values of your map will be Longs anyway (collections cannot contain primitive types, save for specialized implementations such as found in GNU Trove), look at #BheshGurung's answer...

You can use the toString function;
public String toString() {
return String.valueOf(map.get("id"))
}
String str = map.get("id").toString();

You have 2 issues here:
You created a *L*ong, not a *l*ong. Therefore you need to cast back to a *L*ong, not a *l*ong.
In order to get the String representation of a *L*ong you must call toString() on it.
Use this:
String str = ((Long)map.get("id")).toString();

Related

How to cast String to the generic information that it represents?

My goal is to cast to a generic type, the information that a String contains, being this information variable between the different Java types. Ex:
String s = "10";
E e1 = (E)s;
String s = "abc";
E e2 = (E)s;
In this example e1 would be an Integer and e2 remains String. I have been searching for a solution during several hours, and the best I have found is a solution with reflection
However it cast to String, indepently if it contains other type of information, causing malfunctions in other parts of the code.
There's some terminological friction between your notion of "generic" (the kind of information that e.g. the 2nd and 3rd characters of "€10.-" might represent) and generic types, which is a Java technical term and concept.
There are some things below, that objects of class String are compatible with. Only Comparable is considered a generic type in the Java technical sense (here it has the type parameter <String>), all the rest is not.
public final class String implements java.io.Serializable,
Comparable<String>, CharSequence, Constable, ConstantDesc
You don't need to cast a String to any of them. You can just do stuff like this:
String s = "10";
CharSequence c = s;
If you go the other way round and you have CharSequence c then you can find out if it is actually String, and if it is, then you can cast. Btw. also the "reflection approach" you referred to tests (clazz.isAssignableFrom) before it casts.
CharSequence c = new StringBuffer("Käse");
if(c instanceOf String) // it is not, it is instanceOf StringBuffer
{
String anotherString = (String) c;
}
What you talked about isn't about casting but converting or evaluating. You can get an Integer from a String using Integer's conversion method valueOf().
Integer two = Integer.valueOf("2");
But it may fail, e.g. if you try this Integer.valueOf("€10.-") you'd get a NumberFormatException. You'd need to pick the numerical part only to make it work Integer.valueOf("€10.-".substring(1, 3))

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

(String) Meaning in Java

Decided to edit this question.
(String) refers to casting.
Ex:
protected String methodA(Vector X) {
return (String) X.get(0);
}
In this case the get method returns an object, and for the methodA to return a String there needs to be a cast to String. And the cast is done as demonstrated.
To my understanding, the (String) is a cast to string. Without being into the details, I suppose that the return type of get is Object, even if the contents are of String type. The cast is necessary to match the return type of method.
This method returns first element in the Vector cast to String.
If X.get(0) returns an Object but the underlying is String then another way besides (String) X.get(0) is to use X.get(0).toString(). That might be more familiar.

Error converting Optional<String> to Integer from TextInputDialog

In this example I have tempSocket1 and tempSocket2 but I really just want one of them. I just included both to show I tried both methods, but I keep getting an error, "the method valueOf(String) in the type Integer is not applicable for the arguments (Optional)." I thought both of these methods were the ones used for converting a string data type to integer, but I'm not sure how the Optional part changes the whole system.
private void showTextInputDialog() {
TextInputDialog changePort = new TextInputDialog("Settings");
changePort.setHeaderText("Change Port");
changePort.setContentText("Please enter port number to be used for establishing connection...");
Optional<String> result = changePort.showAndWait();
result.ifPresent(e -> {
Integer tempSocket1 = Integer.valueOf(result);
Integer tempSocket2 = Integer.parseInt(result);
}
);
}
To convert an Optional to an Integer, it is necessary to invoke the get() method before the conversion.
Optional<String> cadena = Optional.of("333");
Integer num = Integer.valueOf(cadena.get());
You see, Integer.valueOf and Integer.parseInt methods need an argument of type String, but you are passing an Optional<String>. So that's why the error occurred. Optional string and string are not the same.
Just think about this, if Optional<String> were the same as String, would ArrayList<String> be the same as String? Would LinkedList<String> be the same as String? What about HashMap<String, Integer>? Would it be both a String and an Integer?
The chaos that treating generic types the same as their generic type arguments would bring is destructive! Imagine calling charAt on an optional string! Without the implementation, no one knows what will happen...
So yeah, never think that generic types are the same types as the generic type parameters.
Just to extend other answers it may looks better using map method, and even more with lambda and method reference:
Optional<String> result = changePort.showAndWait();
Integer tempSocket = result.map(Integer::valueOf).orElse(8080);
You're trying to pass an Optional<String> instead of a normal String. You need to fetch the string first with .get() before converting your result to an integer. Or use result.ifPresent(e ...) that will automatically unwrap the optional value and convert it to an Integer.
Optional<String> result = changePort.showAndWait();
result.ifPresent(e -> {
Integer tempSocket1 = Integer.valueOf(e);
Integer tempSocket2 = Integer.parseInt(e);
}
);

Indicate datatype from a input string?

For example i have a string input "int",can i declare a variable base on that input?
(Not switch check please). I mean something like this (pseudo-code) or similar:
String str="int";
new (variable_name,"int");
// create new variable with int datatype.
You can do this:
String className = "MyClass";
Object obj = Class.forName(className).newInstance();
But it won't work for primitive types.
If instead of using primitive types you will use cannonical name of Object based class you can try to do this
public Object loadClass(String className) {
return Class.forName(className).newInstance(); //this throw some exceptions.
}
Not practically, Java is strongly typed and the type of all variables must be known at compile time if you are to do anything useful with them.
For example, you could do something like this;
String str = "java.lang.Integer";
Class clazz = Class.forName(str);
Object o = clazz.newInstance();
..which will give you an Object o whose type is determined at runtime by the value of the String str. You can't do anything useful with it though without first casting it to the actual type, which must be known at compile time.

Categories