Re: Generic generics help
[Removed crossposting]
wizard of oz escribi=F3:
I'm trying to write a data class using generics. This class is a Sparse=
Matrix meaning that it can have many dimensions but not many entries
(e.g. a 100 by 100 matrix, but there might only be 10 entries in the
matrix).
Here is what I started with:
public class SparseMatrix<R, C, E> {
private TreeSet<R> rowHeaders = new TreeSet<R> ();
private TreeSet<C> colHeaders = new TreeSet<C> ();
public void add (R rowKey, C colKey, E element) {
ensureExists (rowHeaders, rowKey);
ensureExists (colHeaders, colKey);
}
I presume there is something more to do in this add(R, C, E) method,
isn't there? Like actually adding the element, I mean. I guess that's
why you say "My first step (...) in my add method".
I think Mark Space hasn't fully understood what you are trying to
achieve, but his suggestion should suffice to cut your code to six
lines, although they are somewhat duplicated, indeed:
public void add(R rowKey, C colKey, E element) {
if (!rowHeaders.contains(rowKey)) {
rowHeaders.add(rowKey);
}
if (!colHeaders.contains(colKey)) {
colHeaders.add(colKey);
}
}
So far I've searched google for the error message and tried various
(random) combinations of ensureExists method signatures, but just can't=
get it to work. The only thing I've found to work is if I duplicate the=
routine and overload it as in:
private void ensureExists (TreeSet<R> treeSet, R key) {
...
private void ensureExists (TreeSet<C> treeSet, C key) {
...
Obviously I'd rather not duplicate the method - that seems silly.
Based on my tiny background on generics, I'd say that, at the very
least, you need to make R and C to be subclasses of another class, and
make sure that rowHeaders and colHeaders use the superclass. Something
like this:
private <T> void ensureExists(TreeSet<T> treeSet, <? extends T> c) {
// Since c has to be a subclass of T, it can fit into the
// TreeSet<T>
}
It's just that I'm not sure how you should define the class signature
to tell the compiler than R and C must be subclasses of T. :-) It
could be something like:
public class <T> SparseMatrix<R<? extends T>, C<? extends T>, E> {
but that's just a guess.
HTH
--
If it's true that we are here to help others,
then what exactly are the OTHERS here for?