How do I override the toString method to display elements in a list in Java?

后端 未结 5 476
醉梦人生
醉梦人生 2021-01-28 02:18

I have been trying to figure this out for hours, but I am unable find an answer that works.

For completeness, I have posted the entire code below. If I do not Override

5条回答
  •  忘掉有多难
    2021-01-28 02:54

    You do not match the signature of Object.toString(). (I usually let my IDE generate a stub, helps plenty ;))

    Just add this to your existing code:

    @Override
    public String toString() {
        return "WordsContainer{" +
                "wordList=(" + toString(wordList) + ")}";
    }
    

    Though, you will have to declare wordList as List.

    UPDATE:

    To clarify the last remark in the original answer:

    In your own wrapper WordsContainer you declare wordList as

    Collection wordList = new ArrayList();
    

    while in your own attempt at implementing toString you use List as parameter type. Therefore, the above code would not work without one other refactoring. Either declare wordList as List

    List wordList = new ArrayList();
    

    or refactor your toString() to take a Collection as argument:

    public String toString(Collection list) {
        String result = " ";
    
        for (Object item : list) {
            result += " " + item.toString();
        }
        return result;
    }
    

提交回复
热议问题