简体   繁体   中英

Where is toString() overridden on java.util.List

I was wondering why this assert works in JUnit:

assertEquals("[String1, String2, String3]", Arrays.asList("String1", "String2", "String3").toString());

I can't see the toString() being overridden anywhere on List or Collection.

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 :

  • AbstractList
  • AbstractQueue
  • AbstractSet
  • ArrayDeque

The element returned by .asList is probably a subclass of AbstractList

Both List and Collection are interfaces. Method toString() is overridden in AbstractCollection .

Anyway it is a bad practice to compare string representations of objects. You should use

assertEquals(expectedList, actualList) instead.

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 . The new implementation has a lot of methods including array comparison utilities.

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.

Object class has implementation of 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.

UPDATED based on UmNyobe comments:

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 .

toString is overriden by ArrayList , the List implementation returned by Arrays.asList()

Here is how the asList method is implemented in the Arrays class.

public static <T> List<T> asList(T... a) {
    return new ArrayList<T>(a);
}

where ArrayList is an static inner class of Arrays :

private static class ArrayList<E> extends AbstractList<E>

Ya, well is not directly overriden by ArrayList but by its ancestor AbstractList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM