HashMap中类的hashCode重写和不重写的区别
hashmap是通过key的hashCode来查找,所以即使我们重写了equals方法,但是如果没有重写hashCode方法,得到的两个对象仍然不相等。如果要使两个实例的对象为一致时,就必须重写hashCode方法
案例:
public class Cat {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Cat(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cat cat = (Cat) o;
return age == cat.age &&
Objects.equals(name, cat.name);
}
//HashMap:链表+数组(Entry)实现
//重写hashCode,创建新对象时,保证它们的hashCode值为一致
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
测试方法
public static void main(String[] args) {
Cat c1 = new Cat("小咪", 11);
Cat c2 = new Cat("小咪", 11);
Cat c3 = new Cat("小黑", 21);
Map<Cat, Object> map = new HashMap<>();
//根据数据一致key获取value
map.put(c1,"999");
//如果类中不重写hashcode的话创建2个对象他们的hashcode值不一致
//下面输出:null true 3
//如果类中重写hashcode的话创建2个对象他们的hashcode值一致
//下面输出:999 true 2
System.out.println(map.get(c2));
//equal方法中重写hashCode方法
System.out.println(c1.equals(c2));
//类中实现hashCode和equals方法,确保存入集合中的对象参数不能为一致(过滤重复数据的对象)
HashSet<Cat> cats = new HashSet<>();
cats.add(c1);
cats.add(c2);
cats.add(c3);
//Cat类不重写hashCode:集合中会插入3个参数,否者只会插入2个(过滤重复数据的对象)
System.out.println(cats.size());
}
linkedHashMap和HashMap的区别
Linkedhashmap是hashmap的子类,实现了hashMap+双向链表。
Linkedhashmap(有序集合)和hashmap(无序集合)区别
//表示hashMap是无序的Map(无序存放数据)
public static void getHashMap(){
HashMap<Object, Object> map = new HashMap<>();
map.put("code","message");
map.put("message","你好!");
map.put("data","hello");
map.put("count","1");
Set<Map.Entry<Object, Object>> entries = map.entrySet();
Iterator<Map.Entry<Object, Object>> iterator = entries.iterator();
while (iterator.hasNext()){
Object key = iterator.next().getKey();
Object value = map.get(key);
System.out.println("key:"+key+",value:"+value);
}
}
//LinkedHashMap是有序存放的Map(按有序存放,取出也是有序)
public static void getLinkedHashMap(){
Map<Object, Object> map = new LinkedHashMap<>();
map.put("code","message");
map.put("message","你好!");
map.put("data","hello");
map.put("count","1");
Set<Map.Entry<Object, Object>> entries = map.entrySet();
Iterator<Map.Entry<Object, Object>> iterator = entries.iterator();
while (iterator.hasNext()){
Object key = iterator.next().getKey();
Object value = map.get(key);
System.out.println("key:"+key+",value:"+value);
}
}
public static void main(String[] args) {
//表示hashMap是无序的
System.out.println("hashMap是无序的存放!");
getHashMap();
System.out.println("LinkedhashMap是有序的存放!");
getLinkedHashMap();
//输出:
// hashMap是无序的存放!
// key:code,value:message
// key:data,value:hello
// key:count,value:1
// key:message,value:你好!
// LinkedhashMap是有序的存放!
// key:code,value:message
// key:message,value:你好!
// key:data,value:hello
// key:count,value:1
}