[英]Where is toString() overridden on java.util.List
I was wondering why this assert works in JUnit:我想知道为什么这个断言在 JUnit 中有效:
assertEquals("[String1, String2, String3]", Arrays.asList("String1", "String2", "String3").toString());
I can't see the toString() being overridden anywhere on List or Collection.我在 List 或 Collection 的任何地方都看不到 toString() 被覆盖。
I'm glad it works, but, still curious.我很高兴它有效,但仍然很好奇。
Arrays.asList
返回一个Arrays#ArrayList
扩展AbstractList
扩展AbstractCollection
实现toString
。
toString is overrided by AbstractCollection which is a superclass of : toString 被AbstractCollection覆盖,它是一个超类:
The element returned by .asList
is probably a subclass of AbstractList
.asList
返回的元素可能是AbstractList
的子类
Both List
and Collection
are interfaces. List
和Collection
都是接口。 Method toString()
is overridden in AbstractCollection
.方法
toString()
在AbstractCollection
中被覆盖。
Anyway it is a bad practice to compare string representations of objects.无论如何,比较对象的字符串表示是一种不好的做法。 You should use
你应该使用
assertEquals(expectedList, actualList)
instead. assertEquals(expectedList, actualList)
代替。
where在哪里
expectedList = Arrays.asList(new String[] {"String1", "String2", "String3"})
or even better in your case:在您的情况下甚至更好:
assertArrayEquals(expectedArray, actualArray)
Please pay attention that you should use newer org.junit.Assert
instead of junit.framework.Assert
.请注意,您应该使用更新的
org.junit.Assert
而不是junit.framework.Assert
。 The new implementation has a lot of methods including array comparison utilities.新实现有很多方法,包括数组比较实用程序。
Object
class has implementation of toString()
. Object
类具有toString()
的实现。 Since every class directly or indirectly extends
to Object
, If a particular class doesn't define toString(), it gets inherited from it's parent classes in the hierarchy.由于每个类都直接或间接地
extends
为Object
,如果一个特定的类没有定义 toString(),它会从层次结构中的父类继承。
UPDATED based on UmNyobe comments:根据UmNyobe评论更新:
In the hierarchy, the very first parent class found which has the required omplementation, will be used.在层次结构中,将使用找到的第一个具有所需补充的父类。 In the question by OP, that parent class will be
AbstractCollection
which overrides toString
from Object
.在 OP 的问题中,该父类将是
AbstractCollection
,它会覆盖Object
中的toString
。
toString
is overriden by ArrayList
, the List
implementation returned by Arrays.asList()
toString
被ArrayList
覆盖, Arrays.asList()
返回的List
实现
Here is how the asList
method is implemented in the Arrays
class.下面是在
Arrays
类中实现asList
方法的方式。
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
where ArrayList
is an static inner class of Arrays
:其中
ArrayList
是Arrays
的静态内部类:
private static class ArrayList<E> extends AbstractList<E>
Ya, well is not directly overriden by ArrayList
but by its ancestor AbstractList
是的,不是直接被
ArrayList
覆盖,而是被它的祖先AbstractList
覆盖
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.