0

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).

3 Answers 3

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

Should do the magic.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.