If it's guaranteed that your object is an Integer
, this is the simple way:
int x = (Integer)yourObject;
In Java Integer
, Long
, BigInteger
etc. all implement the Number
interface which has a method named intValue
. Any other custom types with a numerical aspect should also implement Number
(for example: Age implements Number
). So you can:
int x = ((Number)yourObject).intValue();
When you accept user input from command line (or text field etc.) you get it as a String
. In this case you can use Integer.parseInt(String string)
:
String input = someBuffer.readLine();
int x = Integer.parseInt(input);
If you get input as Object
, you can use (String)input
, or, if it can have an other textual type, input.toString()
:
int x = Integer.parseInt(input.toString());
In Java there are no pointers. However Object
has a pointer-like default implementation for hashCode()
, which is directly available via System.identityHashCode(Object o)
. So you can:
int x = System.identityHashCode(yourObject);
Note that this is not a real pointer value. Objects' memory address can be changed by the JVM while their identity hashes are keeping. Also, two living objects can have the same identity hash.
You can also use object.hashCode()
, but it can be type specific.
In same cases you need a unique index for each object, like to auto incremented ID values in a database table (and unlike to identity hash which is not unique). A simple sample implementation for this:
class ObjectIndexer {
private int index = 0;
private Map<Object, Integer> map = new WeakHashMap<>();
public int indexFor(Object object) {
if (map.containsKey(object)) {
return map.get(object);
} else {
index++;
map.put(object, index);
return index;
}
}
}
Usage:
ObjectIndexer indexer = new ObjectIndexer();
int x = indexer.indexFor(yourObject); // 1
int y = indexer.indexFor(new Object()); // 2
int z = indexer.indexFor(yourObject); // 1
In Java enum members aren't integers but full featured objects (unlike C/C++, for example). Probably there is never a need to convert an enum object to int
, however Java automatically associates an index number to each enum member. This index can be accessed via Enum.ordinal()
, for example:
enum Foo { BAR, BAZ, QUX }
// ...
Object baz = Foo.BAZ;
int index = ((Enum)baz).ordinal(); // 1