search

Home  >  Q&A  >  body text

Java1.8 JDK源码中,对两个类进行 按位与 操作是什么意思?

Java容器类库中的Map接口(java\util\Map.java)中有一个Entry接口(java\util\Map.java),其中有几个接口方法用到了类和类的按位与操作,即类和类之间有 & 操作符,后面是一个lambda表达式,如下图:

源码如下:

        public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
            return (Comparator<Map.Entry<K, V>> & Serializable)
                (c1, c2) -> c1.getKey().compareTo(c2.getKey());
        }

请问:
1)对两个类进行按位与操作时什么意思?
2)Comparator接口(java\util\Comparator.java)有两个未实现方法,一个传入一个参数,一个传入两个参数,该lambda表达式是怎么工作的?只实现了一个方法就可以使用吗?Comparator部分源码如下:

public interface Comparator<T> {
    int compare(T o1, T o2);
    boolean equals(Object obj);
}
PHP中文网PHP中文网2767 days ago467

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 17:11:08

    This is not bitwise AND, it is the new syntax of Java8, which means that two classes (interfaces) are satisfied at the same time. Equivalent to:

    return (Comparator<Map.Entry<K, V>>) (Serializable)
       (c1, c2) -> c1.getKey().compareTo(c2.getKey());

    Second question, the default implementation in equals方法在Object中已经实现了。之所以在Comparator中“多此一举”列出来,主要是为了提醒而不是强制,因为Object may be inappropriate and often needs to be modified.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:11:08

    This is the new syntax of JAVA8. How is it possible for a class to do bitwise AND

    reply
    0
  • Cancelreply