【问题标题】:Android ArrayList "B" clears when I call clear on ArrayList "A"当我在 ArrayList "A" 上调用 clear 时,Android ArrayList "B" 会清除
【发布时间】:2022-01-14 09:56:55
【问题描述】:

我正在使用这个问题How to filter a RecyclerView with a SearchView 的第二个答案。我只更改了 ArrayLists 的名称,因此代码是相同的。问题是当我清除主 ArrayList 时,由于某种原因,辅助列表也会清除。除非我遗漏了一些明显的东西,否则这不应该发生。下面附上代码;

这是我的构造函数;

public CustomFoodAdapter(Context context, ArrayList<Foods> foodsArray) {
        this.context = context;
        this.foods = foodsArray;
        this.foodsCopy = foodsArray;
    } 

这就是我调用的方法;

public void filter(String text) {

        System.out.println("Foods copy: "+foodsCopy.size()); // Size is 54
        foods.clear();
        System.out.println("2 Foods copy: "+foodsCopy.size()); // Size is 0 (???)
        if(text.isEmpty()){
            foods.addAll(foodsCopy);
        } else{
            text = text.toLowerCase();
            System.out.println("Length is: "+foodsCopy.size());
            for(Foods item: foodsCopy){
                System.out.println("Food name: "+item.foodName);
                if(item.getFoodName().toLowerCase().contains(text)){
                    foods.add(item);
                }
            }
        }
        notifyDataSetChanged();
    }

【问题讨论】:

    标签: android arraylist custom-adapter


    【解决方案1】:

    这是因为您复制的是内存引用中的列表,而不是内容本身。

    因此,在CustomFoodAdapter 构造函数中,您需要创建一个包含foodsArray 内容的新数组列表。

    应该是这样的:

    public CustomFoodAdapter(Context context, ArrayList<Foods> foodsArray) {
            this.context = context;
            this.foods = new ArrayList<>(foodsArray);
            this.foodsCopy = new ArrayList<>(foodsArray);
    }
    

    【讨论】:

    • 你是绝对正确的。非常感谢,等系统允许我会接受的。
    猜你喜欢
    • 2021-11-07
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2012-12-26
    • 2013-04-06
    • 2014-10-17
    相关资源
    最近更新 更多