How to cast an Object to an int

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

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

相关标签:
19条回答
  • 2020-11-27 10:26
    int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
        ArrayList list = null;
        Statement statement = conn.createStatement();
        ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
        while (result.next()) {
            list.add(result.getInt(1));
        }
        statement.close();
        int id[] = new int[list.size()];
        for (int i = 0; i < id.length; i++) {
            try {
                id[i] = ((Integer) list.get(i)).intValue();
            } catch(NullPointerException ne) {
            } catch(ClassCastException ch) {}
        }
        return id;
    }
    // enter code here
    

    This code shows why ArrayList is important and why we use it. Simply casting int from Object. May be its helpful.

    0 讨论(0)
  • 2020-11-27 10:27
    int i = (Integer) object; //Type is Integer.
    
    int i = Integer.parseInt((String)object); //Type is String.
    
    0 讨论(0)
  • 2020-11-27 10:28

    You have to cast it to an Integer (int's wrapper class). You can then use Integer's intValue() method to obtain the inner int.

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

    Finally, the best implementation for your specification was found.

    public int tellMyNumber(Object any) {
        return 42;
    }
    
    0 讨论(0)
  • 2020-11-27 10:31

    You can't. An int is not an Object.

    Integer is an Object though, but I doubt that's what you mean.

    0 讨论(0)
  • 2020-11-27 10:32
    @Deprecated
    public static int toInt(Object obj)
    {
        if (obj instanceof String)
        {
             return Integer.parseInt((String) obj);
        } else if (obj instanceof Number)
        {
             return ((Number) obj).intValue();
        } else
        {
             String toString = obj.toString();
             if (toString.matches("-?\d+"))
             {
                  return Integer.parseInt(toString);
             }
             throw new IllegalArgumentException("This Object doesn't represent an int");
        }
    }
    

    As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.

    0 讨论(0)
提交回复
热议问题