3

Here is an example:

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;
    }
}

The size method is the same for all primitive arrays. Is there a way to avoid this redundancy?

Eran
  • 387,369
  • 54
  • 702
  • 768
qed
  • 22,298
  • 21
  • 125
  • 196
  • Is this a question about using primitive types as generics or about a generalized way to find the length of a primitive array? – Jason C Nov 16 '14 at 13:17
  • It's about using primitive types as generics. – qed Nov 16 '14 at 13:18
  • As for your specific example, `public static int size (Object o) { return java.lang.reflect.Array.getLength(o); }` can be used as a replacement for your array cases. It's almost equivalent overall behavior to your example except `size(...)` will now accept any type and thrown an `IllegalArgumentException` at run-time, rather than a compile-time error on unimplemented types. – Jason C Nov 16 '14 at 13:28
  • Does this have any drawbacks performance-wise? – qed Nov 16 '14 at 16:07
  • 1
    I'm not sure, you could measure it. However, I guarantee your performance bottleneck, if any, will not be in determining the size of the array. Anything else you are doing will dwarf this by a large factor. – Jason C Nov 16 '14 at 18:57

1 Answers1

4

No, there is not. That's the price of working with primitives.

You can see examples of this unavoidable redundancy in many methods in the java.util.Arrays class, where each kind of primitive array has a different method (examples : copyOf, sort, swap, etc...).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    Addendum: In the OP's specific example case, `Array.getLength()` can be used on any array type (parameter is `Object`, length is determined via reflection). – Jason C Nov 16 '14 at 13:33