简体   繁体   中英

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

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 the toString method, I get the representation for the hashcode for the object.

I tried using the following:

 public  String toString(List<?> list) {
String result = " ";
    for (int i = 0; i < list.size(); i++) {
        result += " " + list.get(i);
    }
    return result;
}

However, this does not seem to help as I still get a reference to the hashcode. I understand that this is because I am not overriding the toString method properly; I get an error when I include the @Override annotation, but this is as far as I have been able to get.

I looked at some other answers that said that overriding the toString method would not be useful in the case of Lists/Collections, but no proper guidance for another alternative was given.

public class WordsContainer {
Collection<String> wordList = new ArrayList<String>();

public void wordGroup1() {
    wordList.add("Ant");
    wordList.add("Almond");
    /// more words
  }

public Collection<String> getRandomWords() {
    wordGroup1();
    LinkedList<String> wordLinkedList = new LinkedList<String>(wordList);
    ArrayList<String> subList = new ArrayList<String>();

    int i = 0;
    while (i < 6) {
        int index = (int) Math.random() * 10;
        if (!subList.contains(wordLinkedList.get(index))) {
            subList.add(wordLinkedList.get(index));
            i++;
        }
    }
    return subList;
}

public  String toString(List<?> list) {
String result = " ";
    for (int i = 0; i < list.size(); i++) {
        result += " " + list.get(i);
      }
    return result;
    }
 }

public class wordsContainerTest {
public static void main(String[] args) {
    wordsContainer list1 = new wordsContainer();

    list1.wordGroup1(); 

    System.out.println(list1);

  }


}

EDIT :

Apologies, I forgot to mention that I tried removing the parameters in the Override method like this:

public  String toString() {
  LinkedList<String> list = new LinkedList<>()
   String result = " ";
   for (int i = 0; i < list.size(); i++) {
    result += " " + list.get(i);
}
return result;

} But when I ran the code, the console displayed nothing. I realize this is because I instantiated an empty list, but I at this point, I didnt know what else to do.

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<String> .

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<String> 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<String> list = new ArrayList<String>();
    list.add("foo");
    list.add("bar");
    String listStringRepr = WordsContainer.getStringRepresentation(list);
    System.out.println(listStringRepr);
}

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<String> wordList = new ArrayList<String>();

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<String>

List<String> wordList = new ArrayList<String>();

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;
}

Since you have provide parameter to your toString() method, it is no more the Object 's class toString() method. It is a new method and works as a overloaded version of Object 's toString() not the overridden version. Remove the parameter. To work the toString() properly you need to have the exactly same method signature -

public String toString(){
   //implmentation
}

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

import java.util.List;
import java.util.LinkedList;
public class WordList {
    List<String> list = new LinkedList<String>();
    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'

package listtostringmethod;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ListToStringMethod {

    enter code here
    public static void main(String[] args) {
        // TODO code application logic here
        //List<String> s = Arrays.asList("a","b","c");
        //s.toString();

        MyList myList = new MyList();
            myList.add("a");
            myList.add("b");
        //myList.toString();
        System.out.println(myList.toString());
    }

}

class MyList extends ArrayList {
    @Override
    public String toString (){
        StringBuffer retVal = new StringBuffer();
        Iterator iterator = this.iterator();
            while (iterator.hasNext()){
                retVal.append(iterator.next()+",");
            }
        return retVal.toString();
    }
}

The code is straight forward. Hope this helps you.

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