为什么从容器 class 而不是 Java 中的实例调用方法

Why calling methods from container class instead of instances of it in Java

我正在努力学习 java collections。但是关于调用 collection 方法,有一种我无法理解的特定语法。喜欢 .toString().sort() e. G。 ;

我不明白为什么我们要从数组 class 或 Collections class 中调用以下方法。对于打印数组,这在 println().

内部调用
Arrays.toString(myArray);

用于排序列表

Collections.sort(myList);

为什么不呢?

myArray.toString();

myList.sort();

谁能指导我完成它?

您不能直接在对象上调用这些静态方法,因为参数不匹配。这些方法绑定到 class 而不是它的特定实例,因此您必须将对象作为参数提供。此外,这些方法做不同的事情:

Arrays.toString(myArray);

是一种打印数组内容的便捷方法。如果您调用 myArray.toString(),则会打印对象的哈希码。

最好用

Arrays.toString(myArray);

而不是

myArray.toString();

因为,如果 myArray 为空,则 myArray.toString() 将抛出 java.lang.NullPointerException 但 Arrays.toString(myArray) 将 return 为空。与 myArray.sort()

相同

你的两个例子的原因不同:

数组类型中没有 toString 的自定义实现。对于 MyType[].toString(),开发人员没有得到数组类型的 "override" toString()。这就是提供助手 Arrays.toString 的原因。数组类型的 toString 实现是从 Object 继承的,它几乎总是没有太大帮助。

List.sortList中的一个default方法,随Java8引入。在此之前,只能使用Collections.sort进行排序.如果您查看 Collections.sort 的来源,它会将排序本身委托给 List.sort。至于为什么一开始就没有在List中,那只能由API设计者来回答了。不过,我能想到的一个原因是一致性(Collections 有许多静态集合方法,而 Java 在版本 8 之前不支持接口中的静态方法)。

Java 的数组 toString() 是打印 [,后跟表示数组元素 类型的字符 ,然后是 @,然后是数组的“ 身份哈希码 ”(将其想象成 "memory address")。

要获得人类可以理解的有意义的东西,您需要 Arrays.toString(myArray);

Arrays don't override toString, There's a static method: java.util.Arrays.toString to rescue.

docs的第一行开始:

The collections framework is a unified architecture for representing and manipulating collections, enabling them to be manipulated independently of the details of their representation. It reduces programming effort while increasing performance. It enables interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters software reuse. The framework is based on more than a dozen collection interfaces. It includes implementations of these interfaces and algorithms to manipulate them.

objective是为了减少代码重复。在 myList.sort() 的情况下,List 接口的所有实现都必须实现 sort 函数,并且每个实现的排序可能在行为上有所不同。但是作为Collectionsclass上的静态方法,List实现不需要实现排序功能。从用户的角度来看,您可以将任何 List 传递给 Collections.sort() 并知道会发生什么。

从 Java 8 开始,此功能可以使用默认方法实现,这就是 List.sort(comparator) 所做的。默认方法允许接口的所有实现接收接口中定义的实现,因此从 Java 8 开始 可以做 myList.sort(),但需要注意的是您必须通过提供比较功能来告诉它如何排序。例如,假设您有一个 List<Integer>mylist.sort(Integer::compareTo)。但是集合框架早于默认方法,因此需要 Collections.sort().

除了Collections.sort()List.sort(comparator),您还可以使用Stream.sorted()myList.stream().sorted().collect(Collectors.toList());