Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i convert an object to an int in Java?

Tags:

java

object

int

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?

like image 978
programmer Avatar asked Dec 10 '22 03:12

programmer


2 Answers

Integer.parseInt()

expects a String. You can use

Integer.parseInt(f.toString())

and override the toString() method in your class.

like image 127
Luchian Grigore Avatar answered Dec 26 '22 16:12

Luchian Grigore


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;
}
like image 21
Trevor Freeman Avatar answered Dec 26 '22 16:12

Trevor Freeman