Home > Net >  How to use generics in Java
How to use generics in Java

Time:12-03

I'm studying Java and would like to know if it's possible to transform the two constructors below in a single constructor but using something like generics or something similar.

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

CodePudding user response:

maybe u want this

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

CodePudding user response:

There are many possibilities for this flexible constructor. Some of them use generics. But you can also use simple polymorphism. Your code doesn't give much context to decide whether generics are the best choice.

But here's some possible solution using generics:

class CustomPage<T> {

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

Then you would use it like this:

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

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