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

后端 未结 5 436
醉梦人生
醉梦人生 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:40

    toString() has no arguments. Overwrite it like so (assuming you are extending a List class):

    @Override
    public String toString() {
        String result = " ";
        for (int i = 0; i < this.size(); i++) {
            result += " " + this.get(i);
        }
        return result;
    }
    

    UPDATE 01

    Ok, it seems that what you really want to do is print the contents of the list that is encapsulated by your WordsContainer.

    Override toString of WordsContainer like so:

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(" "); // remove this if you do not want two spaces at the front of the returned string
        for (int i = 0; i < this.wordList.size(); i++) {
            sb.append(" " + this.wordList.get(i).toString());
        }
        return sb.toString();
    }
    

    Note that you have to change the declaration of wordList to be of type List.

    UPDATE 02

    This answers the followup question in comments.

    You can declare a static utility method that builds a string representation of the contents of any given list of strings like so:

    public static String getStringRepresentation(List list) {
        StringBuilder sb = new StringBuilder();
        sb.append(" "); // remove this if you do not want two spaces at the front of the returned string
        for (int i = 0; i < list.size(); i++) {
            sb.append(" " + list.get(i).toString());
        }
        return sb.toString();
    }
    

    And use this method like so:

    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("foo");
        list.add("bar");
        String listStringRepr = WordsContainer.getStringRepresentation(list);
        System.out.println(listStringRepr);
    }
    

提交回复
热议问题