MinMax return mechanics. How does it work on this Shildt’s code example?

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..

Could you please explain it? Thanks!

Answer

Only for the iteration where i=1, vals[1].compareTo(vals[0]) comparison is done, in which case v=6. Consider the case i=3 for the given for-loop. Here vals[3], which is 8, is compared with the value of v (which is 6 since it was updated before). Since 8 is larger than 6, the value of v is updated to 8 in this iteration.

Leave a Reply

Your email address will not be published. Required fields are marked *