Another exercise of Java generics:
import java.util.Collection;
/**
* Created by IDEA on 16/11/14.
*/
public class Size {
public static <T, I extends Iterable<T>> int size(I data) {
final int size;
if (data instanceof Collection) {
size = ((Collection<T>) data).size();
} else {
int counter = 0;
for(Object i : data) {
counter++;
}
size = counter;
}
return size;
}
public static int size(int[] data) {
return data.length;
}
public static int size(double[] data) {
return data.length;
}
public static int size(String[] data) {
return data.length;
}
}
import java.util.ArrayList;
import java.util.List;
/**
* Created by IDEA on 16/11/14.
*/
public class TestSize {
public static void main(String[] args) {
int[] x = {1, 2, 3};
List<Integer> y = new ArrayList<>();
y.add(1);
y.add(2);
System.out.println(Size.size(x));
System.out.println(Size.size(y));
}
}