我试图了解ArrayList.indexOf()为什么返回-1吗?
我创建了一个简单的类,在其中实现了自定义等于,以便可以将类的实例与字符串进行比较。
public class Currency {
final private String code;
final private String unicodeHex;
final private String name;
public Currency(String code, String unicodeHex, String name) {
this.code = code;
this.unicodeHex = unicodeHex;
this.name = name;
}
public String getCode() {
return code;
}
public String getSymbol() {
return unicodeHex;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (o instanceof Currency) {
Currency currency = (Currency) o;
return code.equals(currency.code);
} else if (o instanceof String) {
String currency = (String) o;
return code.equals(currency);
} else return false;
}
@Override
public int hashCode() {
return Objects.hash(code);
}
@Override
public String toString() {
return "Currency{" +
"code='" + code + '\'' +
", unicodeHex='" + unicodeHex + '\'' +
", name='" + name + '\'' +
'}';
}
}
现在我需要在ArrayList中找到该类的实例。
List<Currency> currencies = new ArrayList<>(Arrays.asList(
new Currency("USD","0024","United States Dollar"),
new Currency("EUR","20ac","Euro Member Countries")));
Log.d(TAG, currencies.toString());
Log.d(TAG,Integer.toString(currencies.indexOf("USD")));
2019-02-13 15:41:50.082 D/CurrencySelector: [Currency{code='USD', unicodeHex='0024', name='United States Dollar'}, Currency{code='EUR', unicodeHex='20ac', name='Euro Member Countries'}]
2019-02-13 15:41:50.082 D/CurrencySelector: -1
我得到: -1
但是:
Currency currency = new Currency("USD","0024","United States Dollar");
Log.d(TAG,Boolean.toString(currency.equals("USD")));
2019-02-13 15:41:50.082 D/CurrencySelector: true
等于应该返回 true 。
ArrayList.indexOf 应使用等于:
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
答案 0 :(得分:5)
尽管currency.equals("USD")
可能会返回true
(由于您的实现),但是"USD".equals(currency)
绝不会返回true
,因为它使用了{的equals
实现{1}}类,要求所比较的实例的类型为String
。
因此,String
将返回currencies.indexOf("USD")
,因为-1
调用o.equals(elementData[i])
的{{1}},而String
不是{{1 }}。