Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to use array look up or if elseif statments?

I was doing a basic programming assignment for a course I'm doing. One of the tasks was to compare two ints and print something along the lines of "5 is less than 10."

Because this exercise was a review, I'm assuming the teacher was expecting an if..else if.

I used the java Integer compare method with an array constant to produce the output. I was wondering in general which approach was better (in terms of speed, memory, clarity, etc)?

Sample code

If method:

int a = 5;
int b = 10;
String text;

if (a < b)
  text = "less than";
else if (a > b)
  text = "greater than";
else
  text = "equal to";

System.out.printf("%d is %s %d", a, text, b);

Array method:

final String[] COMPS = {"less than", "equal to", "greater than"};

int a = 5;
int b = 10;
int cmp = Integer.compare(a, b) + 1;

System.out.printf("%d is %s %d", a, COMPS[cmp], b)
like image 797
Phillip Wall Avatar asked Dec 15 '22 20:12

Phillip Wall


1 Answers

For clarity, I would not separate out the text into a variable at all.

if (a < b)
  System.out.printf("%d is less than %d%n", a, b);
else if (a > b)
  System.out.printf("%d is greater than %d%n", a, b);
else
  System.out.printf("%d is equal to %d%n", a, b);

This also gives you more flexibility in how the sentence is structured, which might be important in other languages.


int cmp = Integer.compare(a, b) + 1;

That seems quite a dangerous thing to do, as it assumes unspecified implementation details (which of course won't change, but still...)

According to the Javadoc, Integer#compare "returns the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y". There is no guarantee that it returns +1 or -1.

like image 177
Thilo Avatar answered Dec 17 '22 10:12

Thilo