在Java的世界里,万物皆为对象,那么Map是一个接口!哈哈
举个例子:
Map<User,String> map=new HashMap<User, String>();
其中User类
package com.map; public class User { private int age; private String name; public int getAge() { return age; } public User(){ super(); } /** * * @param age * @param name */ public User(int age,String name){ super(); this.age=age; this.name=name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { System.out.println("运行了hashCode"); final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
运行
package com.map; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MapTest { public static void main(String[] args) { // TODO Auto-generated method stub User user=new User(10,"小明"); User user1=new User(12,"小里"); Map<User,String> map=new HashMap<User, String>(); map.put(user, "小明"); map.put(user1, "kk"); Iterator<User> iter=map.keySet().iterator(); while(iter.hasNext()){ User user2=iter.next(); String name=map.get(user2); } } }
得到输出
运行了hashCode 运行了hashCode
HashMap--hash 就是每个对象都拥有的一个方法,
Map默认长度是16,通过key的hash值得到它所在的位置。如果值相同则放在之前值的后面,是一个链表结构
利用debug模式,选择“查看”(watch)会得到
Map有很多个实现类,ConcurrentHashMap 、Hashtable、HashMap、
参考:http://blog.csdn.net/renfufei/article/details/17287729
时间: 2024-10-12 17:05:05