Java Generics Example

Can someone please tell me how can I make this code more general? I tried several ways, but I am trying to replace the "Integer" part of the code. The code should pass the function as a parameter to another function in order to increase the list of ints (but obviously, if that were common, these would 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); 
}
+3
source share
1 answer

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);
}
+2
source

Source: https://habr.com/ru/post/1785672/


All Articles