I'm working in Java and I would like to convert an Object to an int.
I do:
Collection c = MyHashMap.values();
Object f = Collections.max(c);
int NumOfMaxValues = Integer.parseInt(f);
But it's not working. It says:
No suitable method for parseInt.
How can I fix that?
Integer.parseInt()
expects a String. You can use
Integer.parseInt(f.toString())
and override the toString() method in your class.
Ideally, you should use generics to your advantage and have something along the lines of the below:
Map<Object,Integer> myHashMap = new HashMap<Object,Integer>();
Collection<Integer> values = myHashMap.values();
Integer value = Collections.max(values);
if (value != null)
{
int myInt = value;
}
You can't just convert any object to an int. How should that work. Think of a class like this:
class Car {
public String name;
public String owner;
}
You need to define a method yourself. Or you have to find out what specific object that is and how to convert it.
Integer.parseInt(f.toString());
Related
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);
I have a problem in dealing with the conversion of integer to string. This is my code :
MyClass getRow;
getRow = (MyClass) getListAdapter().getCount();
I found an error on this line: Cannot cast from int to MyClass
This is my MyClass ListView Adapter :
public String toString() {
return myclass;
}
Solved
I have found a solution by adding a few tricks to convert an integer to a string, like this :
int i ;
i = getListAdapter().getCount();
String str = String.valueOf(i);
TextView totalRow = (TextView) findViewById(R.id.totalRow);
totalRow.setText(str);
thanks for all of your answers, awesome Stackoverflow !
int is a primitive and not a class, so the compiler is correct. Why do you expect that an int transform magically into MyClass? What are you trying to do here?
If I understand you correct, you must assing the value of getRow() to your class somehow (either via a setter, by constructor or by accessing the member) and then you can use MyClass. Of course if you want to convert the int to a String object, you have to convert it:
String s = String.valueof(integervalue);
You cannot cast an int to an Object. In the first row you mention you are exactly doing that. getCount() returns an int and you try to cast it to (MyClass).
You never cast primitives to objects in java.
No, you cannot cast this. However, you can achieve a similar effect if you create a constructor for MyClass which accepts an integer as input. So something like:
public MyClass(int x) {
// do stuff to convert as you see fit here
}
then when using it, you do:
getRow = new MyClass( getListAdapter().getCount());
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();
I have a method which return type is string below is the method
public String getHwIdentifier();
Now I am using this method ..
String s = till.getHwIdentifier();//return type of this method is string
I want to cast it in integer that is something like this
Int i = till.getHwIdentifier();
Please advise how take integer means how to cast it..
try parseInt from Integer class.
Integer.parseInt(till.getHwIdentifier());
but mind you, it'd throw NumberFormatException if the string is not a valid integer representation
Use parseInt(String s) method of Integer class which takes String and converts it to intif it is a number or throws NumberFormatException like this :
int i = Integer.parseInt(till.getHwIdentifier());
Pass the instance of the String to Integer.valueOf(String s).
So in your case:
Integer i = Integer.valueOf(till.getHwIdentifier);
See http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28java.lang.String%29 for more details.
There is no Java type/class named Int. There's int type and it's encapsulating Integer class.
You can parse an integer in a String to the int value with Integer.parseInt("1234");, or get the Integer value with Integer.valueOf("1234");. But notice if the String doesn't represent an integer you'll get a NumberFormatException.
String s = till.getHwIdentifier();//return type of this method is string;
try
{
Integer a = Integer.valueOf(s);
int b = Integer.parseInt(s);
}
catch (NumberFormatException e)
{
//...
}
Note: You could use Integer a = Integer.decode(s);, but Integer c = Integer.valueOf(s); is preferred as it won't create new objects if possible.
String s = till.getHwIdentifier();
int i = Integer.parseInt(s);
Make sure that your string is in the form of an integer. If your string contains xyz then you will get a java.lang.NumberFormatException.
I have a clas called as MyFunctions that defines different functions func1, func2, etc. Also I have a class Process that stores the function name assigned to the object of this class:
Process p1 = new Process();
String fName1 = "func1";
p1.setFunctionName(fName1);
Process p2 = new Process();
String fName2 = "func2";
p2.setFunctionName(fName2);
In order to run a proper function, I do the following:
MyFunctions f = new MyFunctions();
if (p.getFunctionName() == "func1") {
output = f.func1(inputdata);
} else if (p.getFunctionName() == "func2") {
output = f.func2(inputdata);
}
I´m not sure that this approach is efficient. Is there any other way to solve this task?
Another question: is it possible to do something like this in JAVA?:
String fName = p.getFunctionName();
output = f."+fName+"(input);
First, this approach is not exactly correct. Never use == to compare objects. Use equals() instead:
MyFunctions f = new MyFunctions();
if ("func1".equals(p.getFunctionName())) {
output = f.func1(inputdata);
} else if ("func2".equals(p.getFunctionName())) {
output = f.func2(inputdata);
}
Second, I'd suggest you to use enum instead.
public enum FunctionInvoker {
func1 {
public Object invoke(MyFunctions o, Object ... arg) {
o.func1(arg[0]);
}
},
func2 {
public Object invoke(MyFunctions o, Object ... arg) {
o.func2(arg[0], arg[1]);
}
},
}
Now the usage looks like:
String functionName = ...; // probably read from file, etc.
Object result = FunctionInvoker.valueOf(functionName).invoke(args);
Java's Reflection API will most likely be useful to you. It allows you (among other things) to find methods in classes at runtime (when you have for example the method name in a string) and call methods that way.
A simple example:
String inputdata = "Hello";
// Finds the method "func1" in class MyFunctions that takes a String argument
Method method = MyFunctions.class.getMethod("func1", String.class);
// Calls the method on a new MyFunctions object, passing in inputdata
// as the argument
Object result = method.invoke(new MyFunctions(), inputdata);
System.out.println("Return value: " + result);
If you have a determined set of functions, then use public static constants to declare the names of the functions.
Example:
public static String FUNCTION1 = "func1";
public static String FUNCTION2 = "func2";
For you second question, yes it is possible using java reflection.
You can use reflection to find the function to execute.
For instance:
f.getClass().getDeclaredMethod(p.getFunctionName).invoke();
I´m not sure that this approach is efficient. MyFunctions f = new MyFunctions();
if (p.getFunctionName() == "func1") {
No. AFAIK it will not work. You are comparing references of String instead of comparing it's content.
if (p.getFunctionName() == "func1")
use .equals instead of == to compare 2 strings.
is it possible to do something like this in JAVA? output = f."+fName+"(input);
You can use reflection in java to do what you want.
Use an enum to decouple:
public enum Function {
ONE {
public void call(Functions functions) {
functions.func1();
},
TWO {
...
};
public abstract void call(Functions functions);
}
An the process:
Process p1 = new Process(Function.ONE);
MyFunctions f = new MyFunctions();
p1.call(f);
Hope you got the idea :)