My code works; I am just seeing if there's an optimized way to write these methods or even better perhaps combine them (since majority of their contents look similar).
public class IntegerUtils {
public static int getMaxValue(int[] array) {
int value = Integer.MIN_VALUE;
if (array.length <= 0) {
throw new IllegalArgumentException("Array is empty.");
}
for (int i = 0; i < array.length; i++) {
if (array[i] > value) {
value = array[i];
}
}
return value;
}
public static int getMinValue(int[] array) {
int value = Integer.MAX_VALUE;
if (array.length <= 0) {
throw new IllegalArgumentException("Array is empty.");
}
for (int i=0; i < array.length; i++) {
if (array[i] < value) {
value = array[i];
}
}
return value;
}
}
Here's my unit test (which works as well):
import org.junit.Test;
public class IntegerUtilsTest {
int[] array = new int[] {1, 2, 3, 58, 47, 229, 40};
@Test
public void shouldBeMaxValue() {
int maxValue = IntegerUtils.getMaxValue(array);
assert(maxValue == 229);
}
@Test
public void shouldBeMinValue() {
int minValue = IntegerUtils.getMinValue(array);
assert(minValue == 1);
}
@Test(expected = IllegalArgumentException.class)
public void shouldBeIllegalArgumentException() {
int[] emptyArray = new int[] {};
int maxValue = IntegerUtils.getMaxValue(emptyArray);
int minValue = IntegerUtils.getMinValue(emptyArray);
}
}
Just seeking feedback regarding optimization and / or code elegance.