Generic methods for primitive types in java

2.6k Views Asked by At

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?

1

There are 1 best solutions below

1
On

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...).