Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a generic static method in java

Tags:

java

generics

I wanted to create a static method which prints the contents of an array.I wrote one for String[] as below

public static void print(String[] a){
    for(String x : a){
    System.out.print(x+", ");
    }
    System.out.println();
}

I thought I could create a method which takes in a generic type ,and modified the code as below

public class ArrayPrinting<E> {

    public static void printArray(E[] a){
        for(E x : a){
            System.out.print(x+", ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        String[] a = {"A","B","C","D","E"};


    }
}

But,this gives a compiler error

'Cannot make a static reference to the non-static type E'

So,how do I create such a method?or is it impossible ? Since this is a static method, I wonder how I can invoke the method without creating an instance. A call like

ArrayPrinting<E>.printArray(a) doesn't look right ..

Can someone help?

like image 252
damon Avatar asked Sep 11 '26 21:09

damon


1 Answers

Try this

public class ArrayPrinting {

    public static <E> void printArray(E[] a){
        for(E x : a){
            System.out.print(x+", ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        String[] a = {"A","B","C","D","E"};
        ArrayPrinting.printArray(a);
    }
}
like image 71
Ravi K Thapliyal Avatar answered Sep 13 '26 11:09

Ravi K Thapliyal



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!