I actually wanted to make a generic method that finds the maximum element in the given elements. I am also extending comparable. Now the issue is that i am going to send elements sometimes as an array and sometimes as an ArrayList . So i needed to make a common method that can accept both of them and returns the maximum. The main issue is that in the the function prototype if i mention box brackets then it doesn't represent an ArrayList and vice versa
1 Answer
Just create two methods with different signatures. You can defer to one method from the other so that you don't repeat the implementation:
public <T> T getMax(T[] array)
{
return getMax(Arrays.asList(array));
}
public <T> T getMax(List<T> list)
{
// actually get the max
}
2 Comments
Kushal Shinde
Do we need a return type of a second method as <T>T? or just a max value?
xtratic
@KushalShinde OP wants the "maximum element in the given elements". In this case
T is the type of those elements and the type of the maximum element, so yes, the method's return type is T.
Arrays.asList()