I need a custom method to check for a list containing an instance of a class and call this method but I do not understand this syntax "Class clazz" and I do not understand What's the second parameter of this method
public static <E> boolean containsInstanceOfOidInrArraylist(List<E> Arraylist, Class<? extends E> clazz) {
for (E e : Arraylist) {
if (clazz.isInstance(e)) {
return true;
}
}
return false;
}
Ok, so the first parameter of the function is a List<E>
named Arraylist
(You shouldn't capitalize variables in Java, name it as such arrayList
).
The second parameter is a Class<? extends E>
Class<? extends E>
named clazz
.
Check manub's explaination of Class<?>
:
Class
is a parameterizable class, hence you can use the syntaxClass<T>
whereT
is a type. By writingClass<?>
, you're declaring aClass
object which can be of any type (?
is a wildcard). TheClass
type is a type that contains meta-information about a class.
So now you know what Class<?>
means, but what about Class<? extends E>
Class<? extends E>
?
<? extends E>
<? extends E>
basically means any class which extends E (or E itself).
So Class<? extends E> clazz
Class<? extends E> clazz
means you have a varaible named clazz
which is E
class or a sub class of E
.
See this tutorial: https://docs.oracle.com/javase/tutorial/java/generics/upperBounded.html
"Upper Bounded Wildcards
You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>
, List<Double>
, and List<Number>
; you can achieve this by using an upper bounded wildcard.
To declare an upper-bounded wildcard, use the wildcard character ('?'), followed by the extends keyword, followed by its upper bound. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces)."
The second parameter is a class that is the same as the class of the objects in the list, or extends it. clazz is used as a variable name because class is a reserved keyword and cannot be used.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.