【问题标题】:Difficulty Comparing Two Arrays In Kotlin在 Kotlin 中比较两个数组的难度
【发布时间】:2022-01-09 00:15:18
【问题描述】:

您好,我似乎无法在 Kotlin 上比较这两个数组。

var temp = ingredientsList.toArray()
var temp2 = chickenTikkaMasala.get(0).ingredients
if(ingredientsList.toArray().contentEquals(chickenTikkaMasala.get(0).ingredients)) {
   Toast.makeText(this, "Chicken Tikka Worked", Toast.LENGTH_SHORT).show()
}

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    contentEquals 函数仅在数组包含相同顺序的相同元素时才返回 true。您的数组没有相同的顺序。 来自文档:

    /**
     * Returns `true` if the two specified arrays are *structurally* equal to one another,
     * i.e. contain the same number of the same elements in the same order.
     *
    

    【讨论】:

    • 有没有办法非结构性地比较两个数组?
    • 您没有看到您问题的其他答案吗?
    【解决方案2】:

    如果您只关心集合中是否存在某个项目,那么您在这里真正处理的是集合,而不是列表或数组。所以你需要将它们作为集合进行比较:

    ingredientsList.toSet() == chickenTikkaMasala.get(0).ingredients.toSet()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      相关资源
      最近更新 更多