How to use generics in Java to return numbers?
•
Java
I have a class similar to the following, but I have a question about using generic return values
import java.util.ArrayList; public class @R_724_2419@<T extends Number> { private ArrayList<T> list; public @R_724_2419@(){ list = new ArrayList<T>(); } public T get(int i){ if(i <list.size()) return list.get(i); else return 0; // Problem } }
When I < 1, I must get 0 (or 0.0 - depending on the value of T) list Size () cannot be empty How to code this correctly?
Solution
If you really want to return 0 by default, you can do this:
public abstract class @R_724_2419@<T extends Number> { private List<T> list; public @R_724_2419@(){ list = new ArrayList<T>(); } public T get(int i){ if(i <list.size()) return list.get(i); else return getDefault(); } protected abstract T getDefault(); }
Then there is an implementation for each number subclass you want to support, such as
public class Integer@R_724_2419@ extends @R_724_2419@<Integer> { @Override protected Integer getDefault() { return 0; } }
and
public class Double@R_724_2419@ extends @R_724_2419@<Double> { @Override protected Double getDefault() { return 0D; } }
wait
A good feature is that it can return any default value, not just zero... And the same principle does not work for any type of object, not just numbers
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码