阅读kvstore\ArrayWrappers.java(4)

ComparableObjectArray 的实现

  private static class ComparableObjectArray implements Comparable<ComparableObjectArray> {

    private final Object[] array;

    ComparableObjectArray(Object[] array) {
      this.array = array;
    }

    @Override
    public boolean equals(Object other) {
      if (!(other instanceof ComparableObjectArray)) {
        return false;
      }
      return Arrays.equals(array, ((ComparableObjectArray) other).array);
    }

    @Override
    public int hashCode() {
      int code = 0;
      for (int i = 0; i < array.length; i++) {
        code = (code * 31) + array[i].hashCode();
      }
      return code;
    }

    @Override
    @SuppressWarnings("unchecked")
    public int compareTo(ComparableObjectArray other) {
      int len = Math.min(array.length, other.array.length);
      for (int i = 0; i < len; i++) {
        int diff = ((Comparable<Object>) array[i]).compareTo((Comparable<Object>) other.array[i]); // 比较时候会强制转换成 Comparable<Object> 类型
        if (diff != 0) {
          return diff;
        }
      }

      return array.length - other.array.length;
    }
  }

  那个强转的地方,如果强转不成功是不是会抛异常啊?

posted @ 2019-09-17 18:03  瑶来瑶去  阅读(122)  评论(0)    收藏  举报