【问题标题】:Parsing Android Voice Recognition Results解析 Android 语音识别结果
【发布时间】:2013-03-26 20:58:42
【问题描述】:
这是我目前的代码:
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String playString = "play";
if( matches.get(0).toString() == playString)
{
// do something
}
语音识别提示拉起来很好,我已经测试过了,实际上可以理解我说的是“玩”这个词。但是,在 if 语句中进行比较时,每次都会失败 - 无论有没有 toString()。我不明白什么?
【问题讨论】:
标签:
android
voice-recognition
【解决方案1】:
回答您的为什么。
运算符 == 测试两个对象引用变量是否引用了完全相同的对象实例。
方法 .equals() 测试被比较的两个对象是否相等——但它们不必是同一对象的完全相同的实例。
示例 #1:
Integer i = new Integer(10);
Integer j = i;
在上面的代码中。 i == j 为真,因为 i 和 j 都指向同一个对象。
示例 #2:
Integer i = new Integer(10);
Integer j = new Integer(10);
在上面的代码中,i == j 是 false,因为尽管它们的值都是 10,但它们是两个不同的对象。
另外,在上面的代码中,i.equals(j) 为真,因为虽然它们是两个不同的对象,但它们是等价的,因为它们代表同一个数字,10。
【解决方案2】:
而不是使用==,例如:if( matches.get(0).toString() == playString)
使用.equals() 喜欢:if( matches.get(0).toString().equals(playString)