0

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
  • Arrays.asList() Commented Mar 15, 2018 at 16:17

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Do we need a return type of a second method as <T>T? or just a max value?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.