Hello, I am having some problems with an assignment.
The assignment is to create a generic class with a type parameter 'T' which needs to be constrained to an upper bound: Number. The class needs to have one field, an ArrayList of type 'T'. I need to provide 3 methods: add() to add an element to the list, largest() to return the largest value in the list and smallest() to do the opposite of largest.
The problem is that beings Number is the superclass of 'T', I am getting errors when trying to use greater/lessthan operators and the compareTo() method to find the largest/smallest value. This is because Number does not support either of these operations.
My question is how can I get my values without using greater/lessthan operators or the compareTo() method? I feel like I'm missing something. It doesn't seem like this should be a hard assignment, but I was up all last night working on it. I tried writing overloaded helper methods to call from largest() named getLargest() which had different returns (Integer, Double etc...). I had tried casting 'T' to the method when calling it but that only worked when I had the Integer method written. As soon as I wrote the Double version an error was thrown that getLargest() was already defined.
Any insight would be greatly appreciated, code to follow.
Edit: I have come up with a way to do this that seems to work, but I'm not sure if it will accomodate all subclasses of number. So far I have tested it on Integer and Long.
Code for new largest() method
Re-Edit: I've tested everything pretty thoroughly and this the revised largest method seems to be the way to go. My biggest fear was that the long value would overflow but it didn't. I've now written the smallest() method and have tested the class with types: Short, Float, Double, Long and Integer. I have not messed with BigDecimal, BigInteger etc... but considering they all take a long value in their constructor, and my method will accommodate long values, I think it will work ok.
Any additional insight would still be appreciated however.