2011年2月17日木曜日

Android の String.indexOf(String,int) メソッドの不具合

Android の java.lang.String クラスの indexOf(String, int) メソッドには不具合がある。第一引数に空文字列を渡すと、常に 0 が返ってくる。過去のバージョンのネイティブコードで書かれた実装も、最新のバージョンの Java で書かれた実装も、同じ不具合を抱えている。

下記のケースにおいて、

  (1) "hello".indexOf("", -1)
  (2) "hello".indexOf("",  2)
  (3) "hello".indexOf("",  5)
  (4) "hello".indexOf("", 10)

(1) ~ (4) はそれぞれ、0、2、5、5 を返すべきだが、Android の String クラスの場合、全てのケースで 0 が返ってくる。


Defect of String.indexOf(String,int) method of Android

indexOf(String, int) method of java.lang.String class of Android contains a bug. If an empty string is given as the first argument, the method always returns 0. Both the native implementation in past versions and the Java implementation in the latest version contain the same defect.

Method calls of the following

  (1) "hello".indexOf("", -1)
  (2) "hello".indexOf("",  2)
  (3) "hello".indexOf("",  5)
  (4) "hello".indexOf("", 10)

should return 0, 2, 5 and 5, respectively, but the String class of Android returns 0 for all the cases.