I am reading Java Shildt The Complete reference and I am wondering about one piece of code thats looks very simple, but I can't understand how it works.
// A generic interface example.
// A Min/Max interface.
interface MinMax<T extends Comparable<T>> {
T min();
T max();
}
// Now, implement MinMax
class MyClass<T extends Comparable<T>> implements MinMax<T> {
T[] vals;
MyClass(T[] o) {
vals = o;
}
// Return the minimum value in vals.
public T min() {
T v = vals[0];
for (int i = 1; i < vals.length; i++)
if (vals[i].compareTo(v) < 0) v = vals[i];
return v;
}
// Return the maximum value in vals.
public T max() {
T v = vals[0];
for (int i = 1; i < vals.length; i++)
if (vals[i].compareTo(v) > 0) v = vals[i];
return v;
}
}
class GenIFDemo {
public static void main(String args[]) {
Integer inums[] = {3, 6, 2, 8, 6};
Character chs[] = {'b', 'r', 'p', 'w'};
MyClass<Integer> iob = new MyClass<Integer>(inums);
MyClass<Character> cob = new MyClass<Character>(chs);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
}
}
//The output is shown here:
//Max value in inums: 8
//Min value in inums: 2
//Max value in chs: w
//Min value in chs: b
I can't understand this one and its output:
// Return the maximum value in vals.
public T max() {
T v = vals[0];
for (int i = 1; i < vals.length; i++)
if (vals[i].compareTo(v) > 0) v = vals[i];
return v;
}
Why the output is 8, if according to the condition, vals[1].compareTo(vals[0])(6>3) > 0 is already true,
so v = 6, not 8.
I can't understand how it finds the max and min value here..
Can you explain it ? Thanks!
Aucun commentaire:
Enregistrer un commentaire