What do I return if there is no numerical solution for my int returning method to find?

StackOverflow https://stackoverflow.com/questions/23112830

  •  04-07-2023
  •  | 
  •  

Pregunta

This is my method for finding a single duplicate within an array. What should I return when an array has no duplicates?

public int findDuplicate(int[] array) {
    Arrays.sort(array);
    int duplicate = 0;
    for(int i = 0; i < array.length; i++)
    {
        if(array[i] == duplicate)
        {
            return duplicate;
        }
        duplicate = array[i];
    }
    return ???;
}
¿Fue útil?

Solución

Three possible solutions come to mind:

  1. 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.

  2. Use Integer and return null. I don't like that kind of APIs personally.

  3. Split your method in boolean hasDuplicate() and int 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?

Otros consejos

Generate and return array of duplicated values. If it has zero size, then no duplicates were found.

I can think of three possible solutions:

  1. You can either return a value that the method should never return under normal circumstances, such as -1 in your case.
  2. You can change the return type to Integer and return a null. Automatic boxing and unboxing can simplify the work needed to make this change.
  3. You can throw an exception.

-1 is the best option. Or add another method for detecting if there is a duplicate in an array or not.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top