Search code examples
javacastingintegerinstanceof

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 // ???
    }
}

Solution

  • Use Integer.valueOf(obj.toString)

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

    This will work for your object array