java中能不能让两个new出来的对象能用==判断放回true

Leafact 2014-12-05 10:25:21
package yzqdayself;

public class TestObjectEquals
{
public String name;
public int age;
public TestObjectEquals(String name,int age){
this.name=name;
this.age=age;
}
@Override
public boolean equals(Object o){
TestObjectEquals t=(TestObjectEquals)o;
if(this.name.equals(t.name)&&this.age==t.age)
return true;
return false;
}
@Override
public int hashCode(){
return name.length()+age;
}
public static void main(String[] args)
{
TestObjectEquals t=new TestObjectEquals("zhangsan", 18);
TestObjectEquals t1=new TestObjectEquals("zhangsan", 18);
System.out.println(t.equals(t1)); //true
System.out.println(t==t1);//是false
}
}
java中比如hashset里面重写hashcode和equals方法。就不会重复添加内容相同的对象,底层貌似是用hashcode和equals判断的,那java如上面 System.out.println(t==t1);//是false,能否返回值是true呢
...全文
880 20 打赏 收藏 举报
写回复
用AI写文章
20 条回复
切换为时间正序
请发表友善的回复…
发表回复
pangna_6029 2018-09-05
  • 打赏
  • 举报
回复
String str1 = new String("abc") + new String("abc");
str1.intern();
String str2 = "abcabc";
System.out.println(str1 == str2);
pangna_6029 2018-09-05
  • 打赏
  • 举报
回复
String a=new String("123");
String b=new String("123");
a="a";
b="a";
System.out.println(a==b);
new出来的值存的是在堆里 只需要把它们放入栈中就可以
done_apple 2015-08-13
  • 打赏
  • 举报
回复
引用 16 楼 dcxy0 的回复:
其实你看hashset的源码就知道hashset其实是用map实现的,添加如下:

 /**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
而map的put底层是这样实现的:

 /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
菜鸟不懂这个问题怎么和map扯上关系了
student-ai 2014-12-08
  • 打赏
  • 举报
回复
其实你看hashset的源码就知道hashset其实是用map实现的,添加如下:

 /**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
而map的put底层是这样实现的:

 /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
lliiqiang 2014-12-08
  • 打赏
  • 举报
回复
==判断地址,不会返回true 可以覆盖equalse方法.
空心兜兜 2014-12-06
  • 打赏
  • 举报
回复
肯定不等吧 对象的实例是唯一的
AceShot 2014-12-06
  • 打赏
  • 举报
回复
引用 2 楼 leafact 的回复:
[quote=引用 1 楼 yll66886 的回复:]
==号比较的是内存地址,
如果你输出之前这样做:
t=t1;
输出的就是true了。

那就是无法用==返回true咯?那我之前看到别人的帖子说重写equals,然后调用重写的equals判断相等,其实本质就是调用了自己定义的方法啊,就比如我说a.equals(b),我调用了自己写的equals方法,这样的比较能说明两个是同一个对象么?=============================================================================================
另外,比如我自己的类里写的新的方法,equals(当前类 类名),这其实是重载了,然后调用equals,他应该会调用自己写的方法,而不会调用Object里面的equals方法吧?其实两个方法都符合,为什么优先调用自己的equals呢[/quote]
对于第一个,的确是调用了自己写的equals方法,然后判断两者是否相等,这里所谓的相等是基于你写的equals方法而言的,可能两个年龄相同的学生对象就是相等的,但这两个对象不是同一个对象,分别有不同的内存地址,所以“这样的比较能说明两个是同一个对象”是不正确的。
对于第二个,是设计好的内部规则,虚拟机会根据方法名先找与自己实际引用类型相同的那个类下面的同名方法(参数类型也是符合的),如果没找到,然后再找超类中符合条件的。
具体参考核心卷 5.1.3动态绑定章节,部分内容如下

Coder_D 2014-12-06
  • 打赏
  • 举报
回复
java如果能和C++一样重载运算符的话可能还可以
姜小白- 2014-12-06
  • 打赏
  • 举报
回复
两个new出来的对象 使用== 比较不可能相等。 重新equals 方法 和 hashcode方法,只是为了通过在比较两个对象的内容上是否相等,从而判断这两个对象是否相等,这个只是业务上的相等,不是java里面的== 的相等。
Panda_熊猫 2014-12-06
  • 打赏
  • 举报
回复
除非你能重写了==
Leafact 2014-12-06
  • 打赏
  • 举报
回复
引用 9 楼 magi1201 的回复:
两个new出来的对象 使用== 比较不可能相等。 重新equals 方法 和 hashcode方法,只是为了通过在比较两个对象的内容上是否相等,从而判断这两个对象是否相等,这个只是业务上的相等,不是java里面的== 的相等。
理解了谢谢你哈
Leafact 2014-12-06
  • 打赏
  • 举报
回复
引用 5 楼 ccs02287 的回复:
肯定不等吧 对象的实例是唯一的
精辟
Leafact 2014-12-06
  • 打赏
  • 举报
回复
引用 4 楼 sum_rain 的回复:
[quote=引用 2 楼 leafact 的回复:] [quote=引用 1 楼 yll66886 的回复:] ==号比较的是内存地址, 如果你输出之前这样做: t=t1; 输出的就是true了。
那就是无法用==返回true咯?那我之前看到别人的帖子说重写equals,然后调用重写的equals判断相等,其实本质就是调用了自己定义的方法啊,就比如我说a.equals(b),我调用了自己写的equals方法,这样的比较能说明两个是同一个对象么?============================================================================================= 另外,比如我自己的类里写的新的方法,equals(当前类 类名),这其实是重载了,然后调用equals,他应该会调用自己写的方法,而不会调用Object里面的equals方法吧?其实两个方法都符合,为什么优先调用自己的equals呢[/quote] 对于第一个,的确是调用了自己写的equals方法,然后判断两者是否相等,这里所谓的相等是基于你写的equals方法而言的,可能两个年龄相同的学生对象就是相等的,但这两个对象不是同一个对象,分别有不同的内存地址,所以“这样的比较能说明两个是同一个对象”是不正确的。 对于第二个,是设计好的内部规则,虚拟机会根据方法名先找与自己实际引用类型相同的那个类下面的同名方法(参数类型也是符合的),如果没找到,然后再找超类中符合条件的。 具体参考核心卷 5.1.3动态绑定章节,部分内容如下 [/quote] 好的,谢谢
youbai57 2014-12-06
  • 打赏
  • 举报
回复
引用 2 楼 leafact 的回复:
[quote=引用 1 楼 yll66886 的回复:] ==号比较的是内存地址, 如果你输出之前这样做: t=t1; 输出的就是true了。
那就是无法用==返回true咯?那我之前看到别人的帖子说重写equals,然后调用重写的equals判断相等,其实本质就是调用了自己定义的方法啊,就比如我说a.equals(b),我调用了自己写的equals方法,这样的比较能说明两个是同一个对象么?============================================================================================= 另外,比如我自己的类里写的新的方法,equals(当前类 类名),这其实是重载了,然后调用equals,他应该会调用自己写的方法,而不会调用Object里面的equals方法吧?其实两个方法都符合,为什么优先调用自己的equals呢[/quote] java中所有类默认继承自Object类,而你的类重写了equals()方法,当你new一个你的类的对象时,能.出什么(调用什么方法、属性),看你的类型;而具体执行哪个方法,是看对象,你创建的你所建的类对象,就执行你的类里面的equals()方法了。总之这是向上造型、重写什么的,你可以去看看书哈!呵呵!
code小生 2014-12-06
  • 打赏
  • 举报
回复
不可以的,==是用来判断基本数据类型的,而new 出来的对象时应用类型变量,用equals来判断是否相等。 你若想让你的第二条输出语句也返回true,应该在输出之前写:t=t1;System.out.println(t.equals(t1));这样就会返回true;但是这样又和第一句没什么区别。 你可以这样测试:TestObjectEquals t2=t; System.out.println(t.equals(t2));));这样返回true就验证了你的要求。
ghx287524027 2014-12-06
  • 打赏
  • 举报
回复
如果对象的属性相等但内存地址不相等的话可以用等号逐一比较他们的属性,这样返回就是true了
_reason 2014-12-06
  • 打赏
  • 举报
回复
Java中没有C++中的运算符重载、指针这样的语法,从而使Java在语法上简单了很多(C++--) 另外,HashSet底层是采用这样的机制来判断的: 1st & ( 2nd || 3rd ) hashCode( ) & ( == || equals( ) ) 对应jdk源码中是这样的:

e.hash == hash && ((k = e.key) == key || key.equals(k))
再加个小例子:

public class TestHashSetJdk{
	public static void main(String[] args){
		Set<Student> set = new HashSet<Student>();
		Student s1 = new Student("小明");
		Student s2 = new Student("小强");
		set.add(s1);
		set.add(s1); //再次添加同一个对象
		set.add(s2); //比较组
		for(Student s : set)
			System.out.println(s.name);
	}
}

class Student{
	String name;
	public Student(String name){
		this.name = name;
	}

	@Override
	public int hashCode(){
		return 1;
	}

	@Override
	public boolean equals(Object obj){
		return false;
	}
}
jy_developer 2014-12-05
  • 打赏
  • 举报
回复
不可以吧 因为内存地址是唯一的
Leafact 2014-12-05
  • 打赏
  • 举报
回复
引用 1 楼 yll66886 的回复:
==号比较的是内存地址, 如果你输出之前这样做: t=t1; 输出的就是true了。
那就是无法用==返回true咯?那我之前看到别人的帖子说重写equals,然后调用重写的equals判断相等,其实本质就是调用了自己定义的方法啊,就比如我说a.equals(b),我调用了自己写的equals方法,这样的比较能说明两个是同一个对象么?============================================================================================= 另外,比如我自己的类里写的新的方法,equals(当前类 类名),这其实是重载了,然后调用equals,他应该会调用自己写的方法,而不会调用Object里面的equals方法吧?其实两个方法都符合,为什么优先调用自己的equals呢
乐乐杨 2014-12-05
  • 打赏
  • 举报
回复
==号比较的是内存地址, 如果你输出之前这样做: t=t1; 输出的就是true了。

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧