create a generic class constructor with additional type constraints

I think the best way is split you implementation on 2 child, something like:

public interface DataSet<T>{
    T getData();

    long getSize();
}

class SimpleDataSet<T> implements DataSet<T>{
    private final long size;
    private final T data;

    public SimpleDataSet(T data, long size) {
        this.data = data;
        this.size = size;
    }

    public T getData() {
        return data;
    }

    public long getSize() {
        return size;
    }
}

class CollectionDataSet<I> implements DataSet<Collection<I>>{
    private final Collection<I> data;

    public CollectionDataSet(Collection<I> data) {
        this.data = data;
    }

    public Collection<I> getData() {
        return data;
    }

    public long getSize() {
        return data.size();
    }
}

But if cannot do it, you can try to do the following:

  public <I> DataSet (Collection<I> input) {
        this.data = (T) input;
        this.size = input.size();
    }

Or

private final Collection<T> collectionData;
public DataSet (Collection<T> input) {
        this.data = null;
        this.collectionData = input;
        this.size = collectionData.size();
    }

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top