两个相同的字符串将不等于true

问题描述

我想比较来自两个不同列表的两个String对象,无论我是否使用 GridViewequals()contentEquals(),始终为假。

与第一个列表的字符串放入其中有什么关系吗?

编辑:这张图片中的日志结果变得很奇怪:

enter image description here

==

以上代码输出日志:

Outcome of the logging

编辑

                        DictWord.dictWords.forEach {
                            Log.i("testen","it is: $it and equals 'black'? - ${it.equals("black")}")
                            Log.i("testen","it is: $it and equals $newWord - ${it.equals(newWord)}")
                            Log.i("testen","it is: $it and equals $newWord - ${it.contentEquals("black")}")
                            Log.i("testen","it is: $it and == $newWord - ${it == newWord}")
                            Log.i("black","it is: 'black' and equals $newWord - ${"black" == newWord}")


...    subStrainsAdapter.addHeaderAndSubmitList(null)
            var textList = mutablelistof<String>()
            var movingText = ""
            thoughtContent.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable) {}
                override fun beforeTextChanged(
                    s: CharSequence,start: Int,count: Int,after: Int) {}
                override fun onTextChanged(
                    s: CharSequence,before: Int,count: Int)
                {movingText += s.last()}
            })

            //SUBSTRAIN INPUT - goes to onSubStrainEditEnd above when ENTER hit
            thoughtContent.setonKeyListener(object : View.OnKeyListener {
                @RequiresApi(Build.VERSION_CODES.Q)
                override fun onKey(v: View?,key: Int,event: KeyEvent): Boolean {
                    return if (event.action == KeyEvent.ACTION_DOWN && key == KeyEvent.KEYCODE_SPACE) {
                        textList.add(movingText)
                        movingText = ""
                        false } else false
                }})

解决方法

newWord似乎没有被修剪。在您的日志中,它前面有多余的空间。

enter image description here

日志中的这两行分别与此代码相对应:

Log.i("testen","it is: $it and equals 'black'? - ${it.equals("black")}")
Log.i("testen","it is: $it and equals $newWord - ${it.equals(newWord)}")

您可以看到您没有在第二行中添加两个空格,但是黑色之前仍然有多余的空格


您应该更正列表或执行newWord.trim(),这会删除所有前导和尾随空格

否则,您应始终使用String.equals(otherString: String)s1 == s2(在kotlin中它们是相同的)

,

您的示例格式错误,我相信会丢失一些代码,但是正如@snachmsm指出的那样,contentEquals是Kotlin中用于数组的方法。您应该使用equals()代替字符串(尽管==是Kotlin的首选方式)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...