0

I've to implement a generic class "myClass" that accepts T as parameter. This T has to be a subclass of Number.

myClass has an "add" method in which I have to add only positive numbers.

public class myClass<T extends Comparable<T>, Number>{
private List<T> listPositive = new LinkedList<>();
public myClass(){}

public void add(T elem){
   if(comp.compare(elem, ???) > 0){ //I would like to compare with 0 but I know I can't.
     listPositive.add(elem);
    }

}
Comparator<T> comp = new Comparator<T>() {
    @Override
    public int compare(T o1, T o2) {
        return o1.compareTo(o2);
    }
};
}

My question is: How can I check if a generic number is positive or negative?

EDIT: Thanks to the answer similar to mine but this din't help me. In fact that question is about to compare two numbers with the same type. I've to check if a certain generic number is negative or positive.

  • Call [`Number#doubleValue`](https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html#doubleValue--) and compare to 0. – Joe Feb 14 '22 at 10:48
  • 1
    Does this answer your question? [Comparing the values of two generic Numbers](https://stackoverflow.com/questions/2683202/comparing-the-values-of-two-generic-numbers) – Joe Feb 14 '22 at 10:50
  • Can you please help me to understand how to use this method? I've never used it before. Shoul I declare a variable first? – FateMintTrio Feb 14 '22 at 10:53
  • 1
    First, you'd need to redefine the generic interface of `MyClass` (adjusted as per naming convention to make things easier): Since `T` needs to be a number and comparable, use `T extends Number & Comparable`. Then you could pass a minimum value to your constructor, e.g. `MyClass(T minimum)`, store it in a field, and finally you can compare this using `minimum.compareTo(elem) <=0` (no need for the comparator here). Then just call your class using the appropriate minimum, e.g. `new MyClass(0L)`, `new MyCLass(0.0)`, `new MyClass(BigDecimal.ZERO)` etc. – Thomas Feb 14 '22 at 10:55
  • With this solution I've to specify the 0 in the constructor parameter. Am I right? Now, if I don't want to pass any parameter to constructor? How can I do this? – FateMintTrio Feb 14 '22 at 11:00

1 Answers1

0

Try something like this:

public class myClass<T extends Number>{
private List<T> listPositive = new LinkedList<>();
  public void add(T elem){
   if(elem.doubleValue() > 0.0){ //or >= if 0 should be a counted as positive
     listPositive.add(elem);
    }
  }
}
3Fish
  • 640
  • 3
  • 18