简体   繁体   中英

Java - get an Integer value from String or int - avoiding instanceof

Is there a single line implementation for the getInt method?

If not - can one implement it without using instanceof ?

public class ParseInt {
    public static void main(String[] args) {
        Object intArr[] = { "131", 232, new Integer(333) };

        for (Object intObj : intArr) {
            System.out.println(getInt(intObj));
        }
    }

    private static int getInt(Object obj) {
        return // ???
    }
}

Use Integer.valueOf(obj.toString)

private static int getInt(Object obj) {
    return Integer.valueOf(obj.toString());
}

This will work for your object array

Try something like...

private static int getInt(Object obj) {
    if (obj instanceof String) {
        return Integer.parseInt((String) obj);
    } else if(obj instanceof Integer){
        return (Integer) obj;
    } else{
        return 0; // or else whatever you want
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM