Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Version 2 of A Java class for calculating size of iterable/array

import java.util.Collection;

/**
 * Created by IDEA on 16/11/14.
 */
public class Size {
    public static int size(Iterable<?> data) {
        if (data instanceof Collection) {
            return ((Collection<?>) data).size();
        }
        int counter = 0;
        for (Object i : data) {
            counter++;
        }
        return counter;
    }

    public static int size(int[] data) {
        return data.length;
    }

    public static int size(double[] data) {
        return data.length;
    }

    public static int size(float[] data) {
        return data.length;
    }

    public static int size(short[] data) {
        return data.length;
    }

    public static int size(boolean[] data) {
        return data.length;
    }

    public static int size(char[] data) {
        return data.length;
    }

    public static <T> int size(T[] data) {
        return data.length;
    }
}
share|improve this question

1 Answer 1

up vote 4 down vote accepted
if (data instanceof Collection) {
    return ((Collection<?>) data).size();
}

This looks like it was meant to improve performance for big collections. But, that instanceof will prevent certain compiler optimizations and you will get huge performance hit for smaller collections. It's likely not worth it, as most collections are small. This could be avoided by having separate method for Collections and Iterables.

Universal utilities like this improve neither readability nor performance. I do not see how Size.size(x) is more readable than x.length or x.size(). The only benefit is that you don't have to think which one to use.

I would leave only method for calculating the size of Iterables and use size()/length for collections/arrays.

/**
 * Created by IDEA on 16/11/14.
 */

Such comments aren't really useful.

public class Size {

I would make the class final and the constructor private as there is no reason to extend or instantiate class with only static methods.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.