我想知道为什么这个断言在 JUnit 中有效:
assertEquals("[String1, String2, String3]", Arrays.asList("String1", "String2", "String3").toString());
我在 List 或 Collection 的任何地方都看不到 toString() 被覆盖。
我很高兴它有效,但仍然很好奇。
谢谢, 德克兰
我想知道为什么这个断言在 JUnit 中有效:
assertEquals("[String1, String2, String3]", Arrays.asList("String1", "String2", "String3").toString());
我在 List 或 Collection 的任何地方都看不到 toString() 被覆盖。
我很高兴它有效,但仍然很好奇。
谢谢, 德克兰
Arrays.asList返回一个Arrays#ArrayListthat extends AbstractListwhich extends AbstractCollection which implementstoString。
If you got to asList code(pressing F3 on asList goes to the declaration in eclipse is the source code is attached) it returns
return new ArrayList<T>(a);
And investigating further Arrays does have a toString overloaded.
List和都是Collection接口。方法toString()在 中被覆盖AbstractCollection。
无论如何,比较对象的字符串表示是一种不好的做法。你应该使用
assertEquals(expectedList, actualList)反而。
在哪里
expectedList = Arrays.asList(new String[] {"String1", "String2", "String3"})
在您的情况下甚至更好:
assertArrayEquals(expectedArray, actualArray)
请注意,您应该使用 newerorg.junit.Assert而不是junit.framework.Assert. 新实现有很多方法,包括数组比较实用程序。
Object类具有toString(). 由于每个类都直接或间接地extends指向Object,如果一个特定的类没有定义 toString(),它会从层次结构中的父类继承。
根据UmNyobe评论更新:
在层次结构中,将使用找到的第一个具有所需补充的父类。在 OP 的问题中,该父类将AbstractCollection覆盖toString.Object
toString被 覆盖ArrayList,List实现由返回Arrays.asList()
这是该asList方法在Arrays类中的实现方式。
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
其中ArrayList是 的静态内部类Arrays:
private static class ArrayList<E> extends AbstractList<E>
是的,好吧不是直接被它的祖先覆盖ArrayList而是被它的祖先覆盖AbstractList