I'm trying to create a generic class that accepts only two types (i.e., Integers and Doubles), as if I would make the class with only Double type, I would be wasting space when I would use the same class for object having only int fields.
Here is the code:
public class Freq implements Comparable {
private String term;
public double frequency;
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
public Freq( String term, int frequency ) {
this.term = term;
this.frequency = frequency;
}
public int compareTo(Object arg) {
if(this.frequency == ((Freq)arg).frequency)
return 0;
else if( this.frequency > ((Freq)arg).frequency ) {
return 1;
}
else
return -1;
}
Now as you can see this class has the mem开发者_如何转开发ber frequency as double, but I would like
to leave that generic but limited to only doubles and integers. However, if I add the generic type such as <T extends Number>
, then compareTo method is failing (it says that operator > is not defined on Numbers or T, ...), and I couldnt figure it out why, hence I need your help.
thanks in advance
You could make it fully generic by using something like this:
public class Freq<N extends Number & Comparable<N>> implements Comparable<Freq<N>> {
private final N frequency;
public Freq(N frequency) {
if (frequency == null) {
throw new IllegalArgumentException("frequency must be non-null");
}
this.frequency = frequency;
}
public int compareTo(Freq<N> other) {
return frequency.compareTo(other.frequency);
}
}
But if object size is your primary concern, then this might not be the best solution, as you need to store a reference to the wrapper object (Double
or Integer
) in addition to the object itself, which is almost certainly larger than just storing a double
itself.
Thus implementing a simple Frequency
class that only provides double
values might actually help safe space.
You can't use primitives for generic types. You can however store any int value in a double, so I would just use a double for everything.
BTW: You may find this simpler
public class Freq implements Comparable<Freq>
public int compareTo(Freq freq) {
return Double.compare(frequency, freq.frequency);
}
Generics don't mix with primitive types. So either you must use types derived from Number
(which means you can't use >
anymore because that works only with primitives) or you can't use generics.
One solution is not to use int
. double
is 64bit and can contain any value that int
can have. Also, since the int
's never have a fraction casting from and do double won't cause loss of precision or rounding errors.
So you can write a class IntFreq
which wraps Freq
and casts all values accordingly.
Try to use this.frequency.doubleValue() for the comparison.
精彩评论