1

I have defined a method in Java like below

public void processData(Object input) {
if(!(input instanceof List || input instanceof Map)) {
      throw new RuntimeException("Invalid argument type. method accept only Map type or List type");
    }

if(input instanceof List) {
//Do something
} else if(input instanceof Map) {
//Do Something
}
}

The above method just works fine. But is there a way to use generics here to show compile time error if user tries calls the method with unexpected argument? Method that only accepts List or Map ? <T extends Collection> wont work because Map is not part of Collection. Is there any other way ?

4
  • 11
    You should not write your method this way. It seems to do very different things depending on whether the parameter is a List vs a Map. You should write two methods instead. Commented Jul 6, 2020 at 6:43
  • As Java allows two methods to have the same name but different parameter types, there is no reason not to write two methods, as @Sweeper suggests. Commented Jul 6, 2020 at 6:58
  • As @Sweeper and @tgdavies mentioned, you can use a mechanic called 'method overloading'. This basically means you can create one method with a List as parameter, and one with a Map as parameter. Both can have the same name. (With a link if you want to read more about method overloading) Commented Jul 6, 2020 at 7:06
  • How to define a method in interface ? Can we have two methods with same name in Interface ? Commented Jul 6, 2020 at 9:30

1 Answer 1

3

The answer is no. The only common super class between Map and List is Object. As others mentioned in the comments, you could simply create two methods, one that accepts a List and another that accepts a Map:

public void processData(List input) {
    // Do something
}

public void processData(Map input) {
    // Do Something
}
Sign up to request clarification or add additional context in comments.

2 Comments

How to define a method in interface ? Can we have two methods with same name in Interface ? And also user needs to override two methods and one leaves empty
@user2731629 please consider accepting the answer if you are satisfied ;)

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.