liguu 2013-12-19 03:18 采纳率: 50%
浏览 1966
已采纳

学到java集合框架中对那个复写equals的疑问,求解答

import java.util.*;
class Student implements Comparable
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Student s)
{
int num = new Integer(this.age).compareTo(new Integer (s.age));
if(num==0)
return this.name.compareTo(s.name);
return num;
}

public int hashCode()
{
    return name.hashCode()+age*34;
}
public boolean equals(Object obj)
{
    if(!(obj instanceof Student))
        throw new ClassCastException("类型不匹配");

    Student s = (Student)obj;
    return this.name.equals(s.name) && this.age==s.age;//这里可不可以写成 return this.name == s.name &&this.age==s.age;
}

public String getName()
{
    return name;
}
public int getAge()
{
    return age;
}

public String toString()
{
    return name+":"+age;
}

}

class MapTest
{
public static void main(String[] args)
{
HashMap hm = new HashMap();

    hm.put(new Student("lisi1",21),"beijing");
    hm.put(new Student("lisi2",22),"shanghai");
    hm.put(new Student("lisi3",23),"nanjign");
    hm.put(new Student("lisi4",24),"wuhan");
    hm.put(new Student("lisi5",25),"changsha");

    //第一种取出方式 keySet
    System.out.println("第一种方式");
    Set<Student> keySet = hm.keySet();

    Iterator<Student> it = keySet.iterator();
    while(it.hasNext())
    {
        Student stu = it.next();

        String addr = hm.get(stu);
        System.out.println(stu+".."+addr);
    }

    System.out.println("第二种方式");
    //第二种取出方式
    Set<Map.Entry<Student,String>> entrySet = hm.entrySet();
    Iterator<Map.Entry<Student,String>> it1 = entrySet.iterator();
    while(it1.hasNext())
    {
        Map.Entry<Student,String> me = it1.next();
        Student stu = me.getKey();
        String addr = me.getValue();
        System.out.println(stu+"..."+addr);
    }
}

}

//Student类中复写equals方法 比较名字的时候可不可以把equals换成==呢??

  • 写回答

2条回答 默认 最新

  • qiang_csd 2013-12-19 05:13
    关注

    String是一个对象,==表示是两个对象是同一个对象,指向同一块内存地址,A.equals(B)表示A的值和B的值相同即可,两者表示的含义不同,所以我认为这里不能换成==

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名