Since arrays and generics don’t mix well, why not use a List instead?"
import java.util.ArrayList;
import java.util.List;
class GenSet<E> {
private List<E> list;
public GenSet() {
list = new ArrayList<>();
}
public void add(E element) {
list.add(element);
}
public E get(int index) {
return list.get(index);
}
}
Why This Works:
ArrayList is inherently generic and avoids type erasure issues with arrays.
Type safety is guaranteed without unchecked casts.
Downside:
Slightly slower than using arrays due to dynamic resizing and additional abstraction.
Usage Example:
GenSet<Double> doubleSet = new GenSet<>();
doubleSet.add(3.14);
Double pi = doubleSet.get(0);Since arrays and generics don’t mix well, why not use a List<E> instead?
import java.util.ArrayList;
import java.util.List;
class GenSet<E> {
private List<E> list;
public GenSet() {
list = new ArrayList<>();
}
public void add(E element) {
list.add(element);
}
public E get(int index) {
return list.get(index);
}
}
Why This Works:
ArrayList is inherently generic and avoids type erasure issues with arrays.
Type safety is guaranteed without unchecked casts.
Downside:
Slightly slower than using arrays due to dynamic resizing and additional abstraction.
Usage Example:
GenSet<Double> doubleSet = new GenSet<>();
doubleSet.add(3.14);
Double pi = doubleSet.get(0);