programmer
programmer

Reputation: 4901

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

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?

Upvotes: 4

Views: 26622

Answers (4)

Trevor Freeman
Trevor Freeman

Reputation: 7232

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

Upvotes: 2

Sachin
Sachin

Reputation: 18747

Integer.parseInt(f.toString());

Upvotes: 1

erikbstack
erikbstack

Reputation: 13254

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.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258568

Integer.parseInt()

expects a String. You can use

Integer.parseInt(f.toString())

and override the toString() method in your class.

Upvotes: 11

Related Questions