Home > OS >  Generics more restricted type for constructor
Generics more restricted type for constructor

Time:02-03

Let's say I will have multiple constructors, other can use T, but one constructor has to use Comparable

I tried to use

public <T extends Comparable<T>>TestT() // does not help

the code

import java.util.ArrayList;

public class TestT<T> {
    private ArrayList<T> arr;
    
    public TestT() {
        arr = new ArrayList<>();
    }
    
    void push(T e){
        arr.add(e);
    }
}

How to make it so TestT constructor will allow only Comparable? Assuming I have other constructors which do not require Comparable

CodePudding user response:

Your question doesn't make much sense since all constructor have the same name. Try using static methods instead:

public class TestT<T> {
    private ArrayList<T> arr;

    public static <X extends Comparable<X>> TestT<X> comparable() {
        return new TestT<>();
    }

    private TestT() {
        arr = new ArrayList<>();
    }
    
    void push(T e){
        arr.add(e);
    }
}

CodePudding user response:

Please see if the below code answers to your requirements:

class TestT<T> {
    private List<T> arr;
    
    // Constructor that receives Comparable
    protected <X extends Comparable<? super X>> TestT(X comparableIn1, X comparableIn2) {
        /* Locate here your logic that transforms the input Comparable to List<T> */
        // some foolish example implementation
        if (comparableIn1.compareTo(comparableIn2) > 0) {
            arr = new ArrayList<>();
        }
        else {
            arr = new LinkedList<>();
        }
    }
    
    // Another Constructor that receives a Collection of Comparable
    protected <X extends Comparable<? super X>> TestT(Collection<X> comparableCollection) {
        /* Locate here your logic that transforms the input Comparable Set to List<T> */
    }

    // Another Constructor that receives something else
    protected TestT(List<T> listOfАrbitraries) {
        arr = listOfАrbitraries;
    }

    void push(T e){
        arr.add(e);
    }
}

// Create different instances by the above Constructor receiving Comparable
TestT<Integer> arrayListOfIntegers = new TestT<>("1","0");
TestT<Object> linkedListOfObjects = new TestT<>("1","2");

Frankly, the notation <X extends Comparable<? super X>> can be simplified to just <X extends Comparable<X>>. In this case your Constructor argument's type will need to implement compareTo(X o) method, while in a manner I wrote above, the Comparable Interface can be also implemented by a method compareTo(<? super X> o) and the method's definition can be also in one of X's super types.

  • Related