AdSense

網頁

2018/5/17

Java 泛型類別的型別符號為空<>是什麼意思

從Java 7開始new一個泛型(generic type)類別時型別可以用<>替代,該類別的型別決定於所分派變數宣告的型別。

例如下面的Box是一個泛型類別Box

public class Box<T> {
  
    private T content;
  
    // constructor
    public Box() {}
  
    public Box(T content) {
        this.content = content;
    }

    public T getContent() {
        return content;
    }

    public void setContent(T content) {
        this.content = content;
    }

}

在Java 7以前建構式要指出泛型的型別。

public class Main {

    public static void main(String[] args) {
    
        Box<String> box1 = new Box<String>();
        Box<Integer> box2 = new Box<Integer>();
        box1.setContent("string");
        box2.setContent(123);
    
        Box<String> box3 = createBoxWithStringContent();
        Box<Integer> box4 = createBoxWithIntegerContent();
    
    
        System.out.println(box1.getContent()); // String
        System.out.println(box2.getContent()); // Integer
        System.out.println(box3.getContent()); // String
        System.out.println(box4.getContent()); // Integer
    }

    public static Box<String> createBoxWithStringContent() {
        return new Box<String>("hello world");
    } 
  
    public static Box<Integer> createBoxWithIntegerContent() {
        return new Box<Integer>(12345);
    }
  
}

而從Java 7開始,建構式的泛型型別可以用<>(diamond operator)省略如下。

public class Main {

    public static void main(String[] args) {
    
        Box<String> box1 = new Box<>();
        Box<Integer> box2 = new Box<>();
        box1.setContent("string");
        box2.setContent(123);
    
        Box<String> box3 = createBoxWithStringContent();
        Box<Integer> box4 = createBoxWithIntegerContent();
    
    
        System.out.println(box1.getContent()); // String
        System.out.println(box2.getContent()); // Integer
        System.out.println(box3.getContent()); // String
        System.out.println(box4.getContent()); // Integer
    }

    public static Box<String> createBoxWithStringContent() {
        return new Box<>("hello world");
    } 
  
    public static Box<Integer> createBoxWithIntegerContent() {
        return new Box<>(12345);
    }
  
}


沒有留言:

AdSense