开发者

Java Generics example

Could someone please advise me how i could make this code more generic? I've tried a few ways but i'm struggling to replace the 'Integer' part of the code. The code has to pass a function in as a parameter to another function to increment a list of ints (but obviously if this was generic it'd be objects).

Thanks in advance

public static void main(String[] args) {
    Integer[] strArray = new Integer[]{1,2,3,4,5};

    List numbers = Arrays.asList(strArray);
    doFunc(numbers, new IFunction() { 
        public void execute(Object o) { 
           Integer anInt = (Integer) o; 
           anInt++;开发者_开发百科
           System.out.println(anInt);
        } 
    }); 
    for(int y =0; y<numbers.size();y++){
        System.out.println(numbers.get(y));
    }
}

public static void doFunc(List c, IFunction f) { 
   for (Object o : c) { 
      f.execute(o); 
   } 
}

public interface IFunction { 
    public void execute(Object o); 
}


Here is a version of your code that uses generics and avoids casts:

public static void main(String[] args)
{
    Integer[] strArray = new Integer[] {1, 2, 3, 4, 5};

    List<Integer> numbers = Arrays.asList(strArray);
    doFunc(numbers, new IFunction<Integer>()
    {
        public void execute(Integer anInt)
        {
            anInt++;
            System.out.println(anInt);
        }
    });
    for (int y = 0; y < numbers.size(); y++)
    {
        System.out.println(numbers.get(y));
    }
}

public static <T> void doFunc(List<T> c, IFunction<T> f)
{
    for (T o : c)
    {
        f.execute(o);
    }
}

public interface IFunction<T>
{
    public void execute(T o);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜