ArrayList 的 contains() 方法如何评估对象? [英] How does a ArrayList's contains() method evaluate objects?

查看:27
本文介绍了ArrayList 的 contains() 方法如何评估对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我创建了一个对象并将其添加到我的 ArrayList.如果我然后创建另一个具有完全相同构造函数输入的对象,contains() 方法是否会将这两个对象评估为相同?假设构造函数没有对输入做任何有趣的事情,并且存储在两个对象中的变量是相同的.

Say I create one object and add it to my ArrayList. If I then create another object with exactly the same constructor input, will the contains() method evaluate the two objects to be the same? Assume the constructor doesn't do anything funny with the input, and the variables stored in both objects are identical.

ArrayList<Thing> basket = new ArrayList<Thing>();  
Thing thing = new Thing(100);  
basket.add(thing);  
Thing another = new Thing(100);  
basket.contains(another); // true or false?

<小时>

class Thing {  
    public int value;  

    public Thing (int x) {
        value = x;
    }

    equals (Thing x) {
        if (x.value == value) return true;
        return false;
    }
}

class 应该如何实现以让 contains() 返回 true?

Is this how the class should be implemented to have contains() return true?

推荐答案

ArrayList implements List 接口.

ArrayList implements the List Interface.

如果您查看 Javadoc for Listcontains 方法你会看到它使用 equals() 方法来评估如果两个对象相同.

If you look at the Javadoc for List at the contains method you will see that it uses the equals() method to evaluate if two objects are the same.

这篇关于ArrayList 的 contains() 方法如何评估对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆