Java: The correct method () method should handle a bad call

I often come across this question. Let's look at a quick example: I got this simple method: it retrieves the position Stringin String[].

public int getStringPosition(String s, String[] text) {
    for (int i = 0; i < text.length; i++) {
        if (text[i].equals(s)) {
            return i;
        }
    }
    return text.length;
}

But what if the string is not in the array? Here it returns the size of the array ( intwhich cannot come from the usual use of the method). He could also come back -1. I would like it to return zero, but that seems impossible.

In any case, this method will be used in the same class by other methods. My question is pretty general, how to handle cases where you cannot return the expected?

+4
source share
8

, , - . .

throw new RuntimeException("String not found");

, , . , -1, String.indexOf List.indexOf. , :

return java.util.Arrays.asList(text).indexOf(s);

. null. , : , . NullPointerException, , , . List.indexOf, null, . , , , . , .

: ? - , ? ( "" , , ​​ .)

, static.

+5

, s text, , , . IllegalParameterException.

, , , . , , return -1.

-1 " ", , .

private static final int STRING_NOT_IN_TEXT=-1;

/**
 * @return first position of 's' in 'text' 
 *         and if 's' is not in 'text' returns NOT_IN_TEXT
 */
public static int getStringPosition(final String s, final String[] text) {
    for (int i = 0; i < text.length; i++) {
        if (text[i].equals(s)) {
            return i;
        }
    }
    return STRING_NOT_IN_TEXT;
}

P.s. , text null , NullPointerReference.

+5

. , , -1. - , , , , , .

+4

, :

a) , "", , -1, "no match found"

b) , IllegalArgumentException

"b", " , findIndex() getIndex(); " " ; null/-1 - . , , , / /. : , , , findXyz() ; , .

, , " ". ; , :

int getIndex(String stringToSearch, List<String> stringsToSearch) {
  return stringsToSearch.indexOf(stringToSearch);

, ... , , , java...

( : , , , , "s"... ).

+2

: String.indexOf(String), -1, . "" String , .

- OO, -

Result search(T something,Set<T> someSet);

, Found NotFound, -; , .

+2

null, . null .

, , - .

+1

null, . Integer int. Integer int . Integer , int. null

public Integer getStringPosition(String s, String[] text)
+1

, :

  • '- 1' " " -
  • - ( , -)
  • Integer null. null - (google "null " )

, ( )

///

public Optional<Integer> getStringPosition(String s, String[] text) {
    for (int i = 0; i < text.length; i++) {
        if (text[i].equals(s)) {
            Optional.of(i);
        }
    }
    return Optional.empty();
}

Optionalavailable in Java 8. If you are using an older version, you can use one of many available implementations (for example, https://google.imtqy.com/guava/releases/19.0/api/docs/com/google/common/base /Optional.html )

+1
source

All Articles