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

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

    Just call toString() with the List element itself. Like so:

    import java.util.List;
    import java.util.LinkedList;
    public class WordList {
        List list = new LinkedList();
        public static void main(String []args) {
           System.out.println(new WordList());
        }
    
        @Override
        public String toString() {
            String result = "";
            list.add("Hello");
    
            list.add("World");
            for (int i = 0; i < list.size(); i++) {
                result += " " + list.get(i).toString();//call toString on element of the list
            }
            return result;
        }
    }
    

    Output: ' Hello World'

提交回复
热议问题