Saturday, April 4, 2015

Some readings today

Here are links to some readings today:

- Java equals()和hashCode()

   Q: 怎样实现正确的equals()方法
   A: 首先,我们需要遵守Java API文档中equals()方法的约定,如下:
    自反性:对于任何非空引用值 x,x.equals(x) 都应返回 true。
    对称性:对于任何非空引用值 x 和 y,当且仅当 y.equals(x) 返回 true 时,x.equals(y) 才应返回 true。
    传递性:对于任何非空引用值 x、y 和 z,如果 x.equals(y) 返回 true,并且 y.equals(z) 返回 true,那么 x.equals(z) 应返回 true。
    一致性:对于任何非空引用值 x 和 y,多次调用 x.equals(y) 始终返回 true 或始终返回 false,前提是对象上 equals 比较中所用的信息没有被修改。

    对于任何非空引用值 x,x.equals(null) 都应返回 false。
    其次,当我们重写equals()方法时 , 不同类型的属性比较方式不同,如下:
    属性是Object类型, 包括集合: 使用equals()方法。
    属性是类型安全的枚举: 使用equals()方法或==运算符(在这种情况下,它们是相同的)。
    属性是可能为空的Object类型: 使用==运算符和equals()方法。
    属性是数组类型: 使用Arrays.equals()方法。
    属性是除float和double之外的基本类型: 使用==运算符。
    属性是float: 使用Float.floatToIntBits方法转化成int,然后使用 ==运算符。
    属性是double: 使用Double.doubleToLongBits方法转化成long , 然后使用==运算符。

  Q: 重写equals()方法为什么一定要重写hashCode()方法
  A: 如果不这样做就会违反Java API中Object类的hashCode()方法的约定,从而导致该类无法很好的用于基于散列的数据结构(HashSet、HashMap、Hashtable、LinkedHashSet、LinkedHashMap等等)。i.e., when search in hashtable based data structure, it'll first find the bucket based on hashCode(), then do compare by equals() to find exact match. Object.hashCode() by default is different for every object. This can't be used when, say, 2 strings "aaa" and "aaa", are different objects so have different hashCode, then you cannot find "aaa" in a container that contains "aaa".


- 揭秘阿里服务互联网金融的关系数据库——OceanBase
  This lacks details though.

JS前台加密,java后台解密实现
   This is not hard to decode though since JS is open.





No comments:

Blog Archive

Followers