java之学习笔记--hashcode获取对象

class XObject{
	public final static Map map=Collections.synchronizedMap(new HashMap()); 它是一个Map,并且线程安全
	public static XObject getObjectByRawHashCode(Integer hashCode){
		return map.get(hashCode);
	}
        /**hashCode()方法是Object类下面的一个方法,供继承类重写,根据对象内存地址计算哈希值    ,String类重写了hashCode方法,并改为根据字符序列来计算哈希值,identityHashCode()方法是S     ystem类中的静态方法,根据对象内存地址来计算哈希值;     **/
	XObject(){
		map.put(System.identityHashCode(this), this);
	}
}
public class MyHashCodeObject extends XObject{
	private String name;
	  
	  public void setName(String s)
	  { 
	     this.name=s;
	  }

	  public String getName()
	  {
	    return this.name;
	  }
	  public static void main(String[] args){
		  MyHashCodeObject my=new MyHashCodeObject();
		  my.setName("abc");
		  System.out.println("hashcode:"+my.hashCode());
		  MyHashCodeObject object=(MyHashCodeObject)XObject.getObjectByRawHashCode(my.hashCode()); 通过hashcode重新得到这个对象
		  System.out.println(object.getName());
	  }



转载于:https://my.oschina.net/u/1182602/blog/347699

你可能感兴趣的:(java)