0

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 // ???
    }
}
Elist
  • 5,313
  • 3
  • 35
  • 73

2 Answers2

1

Use Integer.valueOf(obj.toString)

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

This will work for your object array

  • This would die in the event that `obj` was `null`. You could use `String#valueOf(Object)` instead, which returns the String `"null"` if the passed argument is `null`. – JonK Nov 03 '14 at 12:16
  • @JonK - `String#valueOf(Object)` will throw `NumberFormatException` instead of `NPE`. Why is your suggestion better? – Elist Nov 03 '14 at 15:31
  • @Elist Really it's a matter of personal preference. It's for you to decide which exception is more meaningful for a given situation. If you would prefer a `NullPointerException` then go for that instead. – JonK Nov 03 '14 at 16:52
0

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
    }
}
Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67