Tuesday, November 3, 2015

Generics Made Easy - Part 2

Double.compare(d1,d2)
·         d1 -- first double to compare
·         d2 -- second double to compare.

0, if d1 is numerically equal to d2;
<0, if d1 is numerically less than d2;
>0, if d1 is numerically greater than d2.

General Format:
package org.generics;
public class MaximumTestFirst {
        public static void main(String[] args) {
                System.out.println(maximum(7.5, 6.5));
        }
        private static double maximum(double d1, double d2) {
                double max = d1;
                if (Double.compare(max, d2) < 0) {
                        max = d2; // d2 is the largest so far
                }
                return max;
        }
}

Generics Standard Format:
package org.generics;
public class MaximumTestFirst {
        public static void main(String[] args) {
                System.out.println(maximum(7.5, 6.5));
        }
        private static <T extends Comparable<T>> T maximum(T d1, T d2) {
                T max = d1;
                if (d2.compareTo(max) > 0) {
                        max = d2; // d2 is the largest so far
                }
                return max;
        }
}

Converting area:
Method type
double
<T extends Comparable<T>> T
Parameter type
(double d1, double d2)
(T d1, T d2)
Differences
Double.compare(max, d2)
d2.compareTo(max)


No comments:

Post a Comment