gpt4 book ai didi

java - contains() 按值比较,而不是引用?

转载 作者:行者123 更新时间:2023-11-29 06:39:36 25 4
gpt4 key购买 nike

我很惊讶地看到 equals() 显然被 ArrayList<String> 覆盖了。 .因为 Collection<> 中的 contains() 显然是比较值,而不是引用。当然,对于 Collection<Object> , 引用将被比较。在下面的程序中,我不应该在第二行得到 false 吗?

public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("Obama");
al.add("Reagan");
al.add("Bush");
al.add("Nyquist");
StringBuffer sb = new StringBuffer();
sb.append("Bush");

System.out.println("compares values? using constants " + al.contains("Bush"));
System.out.println("compares values? using local variable " + al.contains(sb.toString()));
}

run:
compares values? using constants true
compares values? using local variable true

最佳答案

Javdaocs for List你是 friend 吗List.contains() 依赖于 .equals():

boolean contains(Object o)
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

String.equals()比较 String 的内容(字符):

public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

关于java - contains() 按值比较,而不是引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14132016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com