Generic array as parameter

I'm trying to make the following function which counts the number of distinct elements in any array:

public static long distinctElements(T[] ar)
{
    return Arrays.asList(ar).stream().distinct().count();
}

The problem here is that I cannot use 'T[] ar' as a parameter (Java says it doesn't know the type T). How can I fix this? This function is in a utility class which does not incorporate the type T (like ArrayList and TreeSet do).

Upvotes: 0

Views: 107

Answers (3)

Hoopje
Hoopje

Reputation: 12932

Java does not know what T is. It would also be a legal name for a class, for example. Therefore, you first have to define that T is a type variable.

You do that by placing it in angles before the return type as follows:

public static <T> long distinctElements(T[] ar) { ... }

Note also that you do not need generics in your case. If A is a subtype of B, then A[] is also a subtype of B[] (this is not the case for generics, by the way). So you can also define your method as follows:

public static long distinctElements(Object[] ar) { ... }

an be able to call it with exactly the same arrays as argument.

Upvotes: 2

Mordechai
Mordechai

Reputation: 16234

public static <T> long distinctElements(T[] ar)

Should do the magic.

Upvotes: 4

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

T is not declared, so the compiler is complaining about that. Declare it at method class:

public static <T> long distinctElements(T[] ar) {
    return Arrays.asList(ar).stream().distinct().count();
}

Also, you could ease the creation of a list by using Arrays#stream:

public static <T> long distinctElements(T[] ar) {
    return Arrays.stream(ar).distinct().count();
}

Upvotes: 1

Related Questions