Three possible solutions come to mind:
Return the matching index or -1 if there is no duplicate. You can't return -1 if you return the duplicate value because it may be -1.
Use
Integer
and returnnull
. I don't like that kind of APIs personally.Split your method in
boolean hasDuplicate()
andint getDuplicate()
and throw an exception if there is no duplicate. This feels wrong, because raising an exception because everything is fine is quite odd.
You might want to change some details of your code, too:
- Copy the array before you sort it, so the callers stuff won't be modified
- Document the corner cases. Which duplicate is found? The first? The last?