【问题标题】:How to use generics in Java [duplicate]如何在 Java 中使用泛型 [重复]
【发布时间】:2022-01-09 11:10:10
【问题描述】:

我正在学习 Java,想知道是否可以在一个构造函数中转换下面的两个构造函数,但可以使用泛型或类似的东西。

public CustomPage(User userInput) {
    List<User> user = new ArrayList<User>();
    user.add(userInput);
    
    this.content = (List<T>) user;
    this.totalElements = (long) 1;
    this.totalPages = 1;
    this.pageSize = 1;
    this.pageNumber = 1;
    this.timestamp = new Date().toInstant().toString();
}

public CustomPage(Person personInput) {
    List<Person> person = new ArrayList<Person>();
    person.add(personInput);
    
    this.content = (List<T>) person;
    this.totalElements = (long) 1;
    this.totalPages = 1;
    this.pageSize = 1;
    this.pageNumber = 1;
    this.timestamp = new Date().toInstant().toString();
}

【问题讨论】:

标签: java generics


【解决方案1】:

这个灵活的构造函数有很多可能性。其中一些使用泛型。但是你也可以使用简单的多态性。您的代码没有提供太多上下文来决定泛型是否是最佳选择。

但这里有一些使用泛型的可能解决方案:

class CustomPage<T> {

    private List<T> content;
    ...
    public CustomPage(T input) {
        List<T> list = new ArrayList<T>();
        list.add(input);
        
        this.content = list;
        ...
    }   
}

然后你会这样使用它:

Person p = new Person();
CustomPage cp1 = new CustomPage<Person>(p);

User u = new User();
CustomPage cp2 = new CustomPage<User>(u);

【讨论】:

    【解决方案2】:

    也许你想要这个

    public CustomPage(T obj) {
            List<T> list = new ArrayList<T>();
            list.add(obj);
    
            this.content = (List<T>) list;
            this.totalElements = (long) 1;
            this.totalPages = 1;
            this.pageSize = 1;
            this.pageNumber = 1;
            this.timestamp = new Date().toInstant().toString();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多