从列表中删除迭代时抛出IndexOutOfBoundsException:Java-> Kotlin

时间:2017-07-18 16:59:58

标签: java android kotlin

代码在Java中运行,但在转换为Kotlin时,它已不再适用。它会抛出IndexOutOfBoundsException

这是最初的Java:

    grid_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            String selectedItem = ((TextView) view.findViewById(R.id.tag_name)).getText().toString();
            for (int j = 0;  j < itemList.size(); j++){
                String tempString = itemList.get(j);
                if(tempString.equals(selectedItem)) {
                    Log.d("Update", "Removing: " + selectedItem);
                    itemList.remove(j);
                }
            }
        }
    });

这是新的Kotlin:

    grid_view!!.onItemClickListener = AdapterView.OnItemClickListener { _, _, _, _ ->
            val selectedItem = (tag_name as TextView).text.toString()
            itemList.indices.forEach {
                val tempString = itemList[it]
                if (tempString == selectedItem) {
                    Log.d("Update", "Removing: " + selectedItem)
                    itemList.removeAt(it)
                }
            }
    }

1 个答案:

答案 0 :(得分:3)

由于indices是第一次初始化,因此从indices删除元素后,forEach操作的List永远不会更改,但{{1}在Java中更改,例如:

size()

对于Kotlin中的可变操作,请改为使用 MutableCollection#removeIf / MutableCollection#removeAll,例如:

//                            v--- `size` is changed after remove item from List
for (int j = 0;  j < itemList.size(); j++){
  //...
}

AND 您的Java代码逻辑错误,例如:

itemList.removeIf { it == selectedItem } // java-8

itemList.removeAll { it == selectedItem } // Kotlin