zoukankan      html  css  js  c++  java
  • [Java] 容器-01 实现 Comparable 接口 / 重写 equals 与 hashCode (1个图 1个类 3个知识点 6个接口)

    import java.util.Collection;
    import java.util.HashSet;
    
    public class BasicContainer {
    	public static void main(String[] args) {
    		Collection c = new HashSet();
    
    		c.add("hello");
    		c.add(new Name("f1", "l1"));
    		c.add(new Integer(100));
    
    		c.remove("hello");
    		c.remove(new Integer(100));
    
    		System.out.println(c.remove(new Name("f1", "l1")));
    		System.out.println(c);
    	}
    }
    
    class Name implements Comparable {
    	private String firstName, lastName;
    
    	public Name(String firstName, String lastName) {
    		this.firstName = firstName;
    		this.lastName = lastName;
    	}
    
    	public String getFirstName() {
    		return firstName;
    	}
    
    	public String getLastName() {
    		return lastName;
    	}
    
    	public String toString() {
    		return firstName + " " + lastName;
    	}
    
    	public boolean equals(Object obj) {
    		if (obj instanceof Name) {
    			Name name = (Name) obj;
    			return (firstName.equals(name.firstName))
    					&& (lastName.equals(name.lastName));
    		}
    		return super.equals(obj);
    	}
    
    	public int hashCode() {
    		return firstName.hashCode(); // 重写 equals 方法必须要重写 hashCode 方法, 当你 Name 类这个对象作为索引,key的时候,就要用到 hashCode
    	}
    
    	public int compareTo(Object o) {
    		Name n = (Name) o;
    		int lastCmp = lastName.compareTo(n.lastName);
    		return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
    	}
    
    }
    

  • 相关阅读:
    第九章 引用
    第八章 指针
    第六章 面向对象
    第五章 if语句与运算符
    第四章 C++数据类型
    第三章 初步了解函数
    第二章 做一个简短的C++程序
    第一章 初始C++
    vs2012 快捷键+方法
    vue如何修改生效日期范围,以及转化成yyyy-mm-dd的格式
  • 原文地址:https://www.cnblogs.com/robbychan/p/3786907.html
Copyright © 2011-2022 走看看