I've managed to use the generics that I'm familiar with in Lists and Maps, but I'll leave a few things to keep in mind as it can be vague when using generics for my own classes.
Generics.java
package generics;
import java.util.ArrayList;
import java.util.List;
public class Generics {
public static void main(String[] args) {
Bean<String> beanForStr1 = new Bean<String>();
beanForStr1.setValue("String");
System.out.println(beanForStr1.getValue());
Bean<Integer> beanForInt1 = new Bean<Integer>();
beanForInt1.setValue(1000);
System.out.println(beanForInt1.getValue());
ExpandBean<Integer> beanForInt2 = new ExpandBean<Integer>();
beanForInt2.setValue(1000);
System.out.println(beanForInt2.getValue());
System.out.println(getAnyBean(beanForStr1).get(0).getValue());
System.out.println(getAnyBean(beanForInt1).get(0).getValue());
System.out.println(getAnyBean(beanForInt2).get(0).getValue());
}
/**
*Generics method
*/
public static <T> List<T> getAnyBean(T args){
List<T> list = new ArrayList<T>();
list.add(args);
return list;
}
}
Bean.java
/**
*Generics class
*/
public class Bean<T> {
private T value;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
ExpandBean.java
package generics;
/**
*Generics class
*You can specify (restrict) such as "some class that inherits the Number class"
*/
public class ExpandBean<T extends Number> {
private T value;
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
It is useful to remember to create the basic part and to organize common processes. The generics class comes sickly, but the point of writing the generics just before specifying the return value of the generics method does not come sickly.
See you again (^_^) Noshi
Recommended Posts