[Java] [Java] Generics class and generics method

1 minute read

Introduction

I am using the generics that are familiar in List and Map, but when using generics for my own class, it may become ambiguous, so keep at least what you want to remember.

Verification environment

  • Eclipse Oxygen.3a Release (4.7.3a)
  • Java8

Source code for verification

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

Notes

It’s helpful to remember to create the base part and organize common processes. The generics class comes thick, but the point of writing generics just before specifying the return value of the generics method does not come up.

See you again (^_^)