Android检查值是否等于Array中的值

时间:2015-11-02 13:52:32

标签: java android arrays

我有一个ArrayList标记;我正在使用listView单击向数组添加值。 在我将值添加到数组之前,检查值是否已存在数组。 我删除它存在的值,否则我将添加值

这就是我的方法,但这些值没有被添加到数组

ArrayList<String> tokens;
tokens = new ArrayList<String>();
...
....
public void onItemClick(AdapterView<?> listView, View view,
                            int position, long id) {
        Cursor cursor = (Cursor) listView.getItemAtPosition(position);
        String selectedtoken = cursor.getString(cursor.getColumnIndexOrThrow("ContactToken"));

        for (int i = 0; i < tokens.size(); i++) {
                if (tokens.get(i).equals(id_To_Search)) {
                    tokens.remove(i);
                }
                else {
                    tokens.add(selectedtoken );
                }
            }
    }
...
...
Log.i("array: ", tokens.toString()); // No values in the array

5 个答案:

答案 0 :(得分:3)

当您最初拥有0个令牌时,您不会添加。

更改为:

boolean removed = false;
for (Iterator<String> iter = tokens.iterator(); iter.hasNext(); ) {
    if (iter.next().equals(id_To_Search)) {
        iter.remove();
        removed = true;
    }
}
if(!removed) {
   tokens.add(selectedtoken);
}

答案 1 :(得分:3)

您只需使用contains方法检查是否存在。

if(!tokens.contains(id_To_Search)){
    tokens.add(selectedtoken);
} else {
    tokens.remove(selectedtoken);
}

答案 2 :(得分:3)

您正在检查数组中的每个元素,如果它是您要存储/删除的项目,然后执行正确的操作。

如果整个数组中存在元素,然后添加或删除它,则应首先找到。

尝试这样的事情:

public void onItemClick(AdapterView<?> listView, View view,
                        int position, long id) {
    Cursor cursor = (Cursor) listView.getItemAtPosition(position);
    String selectedtoken = cursor.getString(cursor.getColumnIndexOrThrow("ContactToken"));

            if (tokens.contains(id_To_Search)) {     
               tokens.remove(id_To_Search);

            }
            else {
                tokens.add(id_To_Search);
            }
}

答案 3 :(得分:2)

如果您的列表为空,则永远不会进入循环,因此您永远不会致电add。如果你开头有任何令牌,你就要为每个现有令牌添加或删除新令牌,这不是你想要的。

我怀疑你想要:

int existingIndex = tokens.indexOf(selectedToken);
if (existingIndex == -1) {
   tokens.add(selectedToken);
} else {
   tokens.remove(existingIndex);
}

或者,您可以使用Set<String>

// Speculatively try to remove it... and add it if you couldn't remove
boolean removed = tokens.remove(selectedToken);
if (!removed) {
   tokens.add(selectedToken);
}

另请注意,您目前正在测试id_To_Search,但之后又添加了selectedToken - 此答案假设您实际上打算在这两个地方使用selectedToken

答案 4 :(得分:1)

当tokens.size()为0时,for循环不会执行。 因此,您永远不会添加令牌,因为最初令牌列表为空。