Created
July 16, 2011 14:47
-
-
Save xZise/1086411 to your computer and use it in GitHub Desktop.
extends clause in Java generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int sumInt(List<Integer> intList) { | |
int sum = 0; | |
for (int i : intList) { | |
sum += i; | |
} | |
return sum; | |
} | |
public static double sumDouble(List<Double> doubleList) { | |
double sum = 0; | |
for (double d : doubleList) { | |
sum += i; | |
} | |
return sum; | |
} | |
public static double sumFail(List<Number> numList) { | |
double sum = 0; | |
for (Number n : numList) { | |
sum += n.doubleValue(); | |
} | |
return sum; | |
} | |
public static int sumWork(List<? extends Number> numList) { | |
double sum = 0; | |
for (Number n : numList) { | |
sum += n.doubleValue(); | |
} | |
return sum; | |
} | |
public static void main(String[] a) { | |
Random r = new Random(); | |
int size = r.nextInt(100) + 10; | |
List<Double> doubles = new ArrayList<Double>(size); | |
List<Number> numbers = new ArrayList<Numbers>(size); | |
List<Integer> integers = new ArrayList<Integers>(size); | |
// Fill arrays | |
for (;size > 0;size--) { | |
int i = r.nextInt(); | |
doubles.add(new Double(i)); | |
if (r.nextBoolean()) { | |
numbers.add(new Double(i)); | |
} else { | |
numbers.add(new Integer(i)); | |
} | |
integers.add(new Integer(i)); | |
} | |
// Work (not handy) | |
int sumInt = sumInt(integers); | |
double sumDouble = sumDouble(doubles); | |
// Don't work, but more handy (one function for all types of number lists) | |
double sumFailInt = sumFail(integers); | |
double sumFailDouble = sumFail(doubles); | |
// Works (as the parameters are matching) | |
double sumFailWorkNumbers = sumFail(numbers); | |
// Work and handy | |
double sumWorkInt = sumWork(integers), | |
double sumWorkDouble = sumWork(doubles) | |
double sumWorkNumbers = sumWork(numbers); | |
/* All sum* variables should be equals! (Maybe some difference due to inaccuracy of double) */ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment