以下内容来自marschen的java4android视频教程
本集主要内容.
1. hashCode的作用
2. hashCode的实现方法.
3. toString的作用
4. toString的实现方法.
什么是hash算法.
任意长度数据 =====>(hash算法)====>散列值(固定长度)
输入1 ===============>>散列值1
输入2 ===============>>散列值2
输入3 ===============>>散列值3
hash算法
所有的类都拥有hashCode()方法.都是object里面的.
hascCode()广泛用于类型框架.
java当中的toString()函数.
User u = new User();
System.out.println(u);
class User{ String name; int age; public User(String name , int age){ this.name = name; this.age = age; } public boolean equals(Object obj){ if(this == obj){ return true; } boolean b = obj instanceof User; if(b){ User u = (User)obj; if(this.age == u.age && this.name.equals(u.name)){ return true; } else{ return false; } } else{ return false; } } public int hashCode(){ int result = 17; result = 31*result + age; result = 31*result + name.hashCode(); return result; } public String toString(){ String result = ""; result = result + "age:" +age +"," +"name:"+name; return result; } }
import java.util.*; class Test{ public static void main(String args[]){ User u = new User("zhangsan",20); //HashMap<User,String> map = new HashMap<User,String>(); //map.put(u,"abc"); //String s = map.get(new User("zhangsan",12)); //System.out.println(s); System.out.println(u); } }