본문 바로가기
Language/Java

Generics

by Zayne 2023. 5. 29.
public class _01_Generics {
    public static void main(String[] args) {
        
        int[] iArray = { 1, 2, 3, 4, 5 };
        double[] dArray = { 1.0, 2.0, 3.0, 4.0, 5.0 };
        String[] sArray = { "A", "B", "C", "D", "E" };

        printAnyArray(iArray);
        printAnyArray(dArray);
        printAnyArray(sArray);
    }

    private static <T> void printAnyArray(T[] array) {
        for (T t : array) {
            System.out.print(t + " ");
        }
        System.out.println();
    }
}

 

The problem with the code is that it tries to pass primitive array types(int[ ], double[ ])

to the 'printAnyArray' method which expects an array of an object type (T[ ] array).

 

Java's generics are not compatible with primitive types like int, double, etc.

They only work with objects. When you try to pass the int[ ] and double[ ] arrays

to the 'printAnyArray' method, you will get a compile error.

 

This is because the 'printAnyArray' method is a generic method,

denoted by the <T> syntax, which means it can accept any type of Object array.

However, in Java, int and double are not Objects, they are primitive types.

 

Here's the correct code : 

package chap_09;

public class _01_Generics {
    public static void main(String[] args) {

        Integer[] iArray = { 1, 2, 3, 4, 5 };
        Double[] dArray = { 1.0, 2.0, 3.0, 4.0, 5.0 };
        String[] sArray = { "A", "B", "C", "D", "E" };


        printAnyArray(iArray);
        printAnyArray(dArray);
        printAnyArray(sArray);
    }

    private static <T> void printAnyArray(T[] array) {
        for (T t : array) {
            System.out.print(t + " ");
        }
        System.out.println();
    }
}

'Language > Java' 카테고리의 다른 글

Anonymous class  (0) 2023.06.14
Array and ArrayList  (0) 2023.05.30
replace, replaceAll  (0) 2023.05.25
Java Collections Framework  (0) 2023.05.25
Java access modifiers  (0) 2023.05.24