Generic methods for primitive types in java [duplicate]

天涯浪子 提交于 2019-12-13 18:26:25

问题


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:


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



来源:https://stackoverflow.com/questions/26957008/generic-methods-for-primitive-types-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!