+ 4
What is generic class and generic function..???
How generic classes and functions are declared and used..?
3 odpowiedzi
+ 3
Generic Function
You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods −
All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).
Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).
+ 1
if you dint understand the above here is simple thing
generic class: We can define our own classes with generics type. A generic type is a class or interface that is parameterized over types. We use angle brackets (<>) to specify the type parameter.
Java Generic Function
Sometimes we don’t want whole class to be parameterized, in that case we can create java generics method. Since constructor is a special kind of method, we can use generics type in constructors too.
0
Here is an example of a generic Java class, which can be used to represent individual entries (key to value mappings) in a map:
public class Entry<KeyType, ValueType> {
private final KeyType key;
private final ValueType value;
public Entry(KeyType key, ValueType value) {
this.key = key;
this.value = value;
}
public KeyType getKey() {
return key;
}
public ValueType getValue() {
return value;
}
public String toString() {
return "(" + key + ", " + value + ")";
} }
This generic class could be used in the following ways, for example:
Entry<String, String> grade = new Entry<String, String>("Mike", "A");
Entry<String, Integer> mark = new Entry<String, Integer>("Mike", 100);
System.out.println("grade: " + grade); System.out.println("mark: " + mark);
Entry<Integer, Boolean> prime = new Entry<Integer, Boolean>(13, true);
if (prime.getValue()) System.out.println(prime.getKey() + " is prime."); else
System.out.println(prime.getKey() + " is not prime.");
It outputs:
grade: (Mike, A) mark: (Mike, 100) 13 is prime.