1. What is a generic type? Examples Show
Answer:1). generics are Java SE 1.5 new feature, the nature of generics is a parameterized type, meaning that the data type being manipulated is specified as a parameter.
2). This type of parameter can be used in the creation of classes, interfaces, and methods, called generic classes, generic interfaces, and generic methods, respectively.
3). the benefits of introducing generics into the Java language are simple and secure.
Cases:
1). Class arraylist<e>: Declares a generic class ArrayList, where E can be substituted with any specific type, Generic types tend to be represented by an uppercase letter.
2). Public boolean Add (E O): E is generic, that is , when you use the add method, you can pass parameters of any type to it. where E is defined in the class.
2. Why generics are used in Java ?
Answer:1). Check type safety at compile time, and all casts are automatic and implicit, increasing the rate of reuse of code.
2). eliminate forced type conversions in your code, and get an additional type-checking layer that prevents someone from saving the value of the error type in the collection.
3. What are parameters? How do I use parameters? Examples Show
Answer:1). use after declaring the class name <E> (E can be any other letter ) , that is, you can specify that the class is a generic class.
2). type parameters can be used where data types are needed in the class, such as property declarations, method declarations, and so on.
4. Why use a generic method? How do I use a generic method? Examples show
Answer:1). A generic method enables the method to change independently of the class.
2). to define a generic method, simply place the generic parameter list before the return value
Example:public <e>e GetX (E x) {
Return x;
}
Note: Whether you have a generic method is not related to whether the class it is in has a generic type. To define a generic method, simply place the generic parameter list before the return value.
5. What is a generic interface? Examples Show
A: generic interface, exactly the same as a generic class
Example: public interface testgenerics<t>{
Public T Gett (T T);
Public String assume (T T);
}
6. what is the comparable interface? Examples show
Answer:1). is a generic interface
public interface comparable<t>{
public boolean Comparableto (T-Other);
}
2). The comparable interface contains a type parameter T, which is the type of object that the class that implements comparable can compare with. This means that if you define a class that implements comparable , such as a String, you want to declare what it can compare to (usually compared to itself)
Example:public class String implements comparable<string>{...}
Generics in Java