How to cast an Object to an int

后端 未结 19 1609
长情又很酷
长情又很酷 2020-11-27 09:58

How can I cast an Object to an int in java?

相关标签:
19条回答
  • 2020-11-27 10:19

    first check with instanceof keyword . if true then cast it.

    0 讨论(0)
  • 2020-11-27 10:20

    Scenario 1: simple case

    If it's guaranteed that your object is an Integer, this is the simple way:

    int x = (Integer)yourObject;
    

    Scenario 2: any numerical object

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

    Scenario 3: parse numerical text

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

    Scenario 4: identity hash

    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.

    Scenario 5: unique index

    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
    

    Scenario 6: enum member

    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
    

    0 讨论(0)
  • 2020-11-27 10:21
    so divide1=me.getValue()/2;
    
    int divide1 = (Integer) me.getValue()/2;
    
    0 讨论(0)
  • 2020-11-27 10:22

    If you're sure that this object is an Integer :

    int i = (Integer) object;
    

    Or, starting from Java 7, you can equivalently write:

    int i = (int) object;
    

    Beware, it can throw a ClassCastException if your object isn't an Integer and a NullPointerException if your object is null.

    This way you assume that your Object is an Integer (the wrapped int) and you unbox it into an int.

    int is a primitive so it can't be stored as an Object, the only way is to have an int considered/boxed as an Integer then stored as an Object.


    If your object is a String, then you can use the Integer.valueOf() method to convert it into a simple int :

    int i = Integer.valueOf((String) object);
    

    It can throw a NumberFormatException if your object isn't really a String with an integer as content.


    Resources :

    • Oracle.com - Autoboxing
    • Oracle.com - Primitive Data types

    On the same topic :

    • Java: What's the difference between autoboxing and casting?
    • Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);
    • Convert Object into primitive int
    0 讨论(0)
  • 2020-11-27 10:23

    If you mean cast a String to int, use Integer.valueOf("123").

    You can't cast most other Objects to int though, because they wont have an int value. E.g. an XmlDocument has no int value.

    0 讨论(0)
  • 2020-11-27 10:25

    If the Object was originally been instantiated as an Integer, then you can downcast it to an int using the cast operator (Subtype).

    Object object = new Integer(10);
    int i = (Integer) object;
    

    Note that this only works when you're using at least Java 1.5 with autoboxing feature, otherwise you have to declare i as Integer instead and then call intValue() on it.

    But if it initially wasn't created as an Integer at all, then you can't downcast like that. It would result in a ClassCastException with the original classname in the message. If the object's toString() representation as obtained by String#valueOf() denotes a syntactically valid integer number (e.g. digits only, if necessary with a minus sign in front), then you can use Integer#valueOf() or new Integer() for this.

    Object object = "10";
    int i = Integer.valueOf(String.valueOf(object));
    

    See also:

    • Inheritance and casting tutorial
    0 讨论(0)
提交回复
热议问题