神马情况下 该重写方法

来源:互联网 发布:centos sftp 编辑:程序博客网 时间:2024/05/16 10:42
/*
*神马情况下 该重写方法
*/
import java.util.*;


class Name
{
private String firstname,lastname;
Name(String firstname,String lastname)
{
this.firstname = firstname;
this.lastname = lastname;
}
public String getfirstname()
{
return firstname;
}

public String getlastname()
{
return lastname;
}
public String toString()//重写tostring方法
{
return firstname+" "+lastname;   
}
}


public class Testcon2
{
public static void main(String[] args)
{
Collection c = new HashSet();
Name n = new Name("f2","l2");
c.add("hello");
c.add(new Name("f1","l1"));

c.add(new Integer(100));
c.remove("hello");
c.remove(new Integer(100));//删除的执行过程为 会逐个比较set内的对象 有字符相同的的删除
                          //要用到equals方法,若此类对象没有重写equals方法则 需要重写equals方法)

System.out.println(c.remove(new Name("f1","l1")));//name 类型的对象没有重写equals方法 所以返回为false
System.out.println(c);
System.out.println(n);//只有重写了tostring方法 返回才是 name类型
}
}