I'm new to programming in java. The below source code is found in a book, when i try to execute the program it is showing some incorrect data.
public class Pair<T> {
private T first;
private T second;
public Pair() {
first = null;
second = null;
}
public Pair(T first, T second) {
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
}
public T getSecond() {
return second;
}
public void setFirst(T newValue) {
first = newValue;
}
public void setSecond(T newValue) {
second = newValue;
}
}
Logic to find the min and max value of the string array
public class ArrayAlg {
public static Pair<String> minmax(String[] arr) {
if (arr == null || arr.length == 0)
return null;
String min = arr[0];
String max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (min.compareTo(arr[i]) > 0)
min = arr[i];
if (max.compareTo(arr[i]) < 0)
max = arr[i];
}
return new Pair<String>(min, max);
}
}
public static void main(String[] args) {
String[] words = { "Mary", "had", "a", "little", "lamb" };
Pair<String> obj = ArrayAlg.minmax(words);
System.out.println("Minvalue " + obj.getFirst());
System.out.println("Maxvalue " + obj.getSecond());
}
If you execute the above program, it displays Minvalue = Mary and MaxValue = little
. The value a
in the String array is the Minimum Value but in this case it is showing Mary
as the Min Value.
Can anyone tell me the better approach to find the Minimum and Maximum value in the String array?