alibaba.fastjson源码分析JSONObject的equals方法
JSONObject的创建
//默认创建一个空的JSONObject 底层使用的是hashMap
//hashMap内部是按照key的ASCII码进行排序
JSONObject jsonObj1 = new JSONObject();
//创建一个内部有序的JSONObject,那么可以使用linkedHashMap
//指定内部数据按照put的顺序有序排序
JSONObject jsonObj2 = new JSONObject(true);
两个JSONObject对象的比较
json1.equals(json2)----> 需不需要考虑内部存储的<k,v>的顺序呢??
源码点进去 json的equals内部 调用的是 this.map.euqals(obj)
public boolean equals(Object obj) {
return this.map.equals(obj);
}
map的equals内部调用什么呢???
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
boolean equals(Object o);
上面清楚的解释到,调用两个对象的entrySet()的equals方法
那么,一起来看看entrySet()内部的equals方法是怎么写的??
/**
* Compares the specified object with this set for equality. Returns
* <tt>true</tt> if the specified object is also a set, the two sets
* have the same size, and every member of the specified set is
* contained in this set (or equivalently, every member of this set is
* contained in the specified set). This definition ensures that the
* equals method works properly across different implementations of the
* set interface.
*
* @param o object to be compared for equality with this set
* @return <tt>true</tt> if the specified object is equal to this set
*/
boolean equals(Object o);
可知,entrySet()的equals方法内部判断依据两点!!!
第一点: 两个set的size,(entrySet的size与传入json内部的key的个数有关)
第二点: set1包含set2的全部元素并且set2包含set1的全部元素 ---->也就是说内部调用的set集合的containsAll方法----> containsAll内部就是通过遍历去判断的!!!
- 所以说,判断两个JSONObject是否相同,并不需要使得内部key顺序相同。