Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic methods for primitive types in java [duplicate]

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?

like image 836
qed Avatar asked Oct 19 '25 02:10

qed


1 Answers

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

like image 200
Eran Avatar answered Oct 21 '25 15:10

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!