Printing Java Collections Nicely (Tostring Doesn't Return Pretty Output)

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

You could convert it to an array and then print that out with Arrays.toString(Object[]):

System.out.println(Arrays.toString(stack.toArray()));

How to pretty print a complex Java object (e.g. with fields that are collections of objects)?

You could try and use Gson. it also serializes Arrays, Maps or whatever....

MyObject myObject = new MyObject();
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
gson.toJson(myObject);

For deserialization use:

gson.fromJson(MyObject.class);

For typed maps see this answer: Gson: Is there an easier way to serialize a map

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

You could convert it to an array and then print that out with Arrays.toString(Object[]):

System.out.println(Arrays.toString(stack.toArray()));

How do I print my Java object without getting SomeType@2f92e0f4?

Background

All Java objects have a toString() method, which is invoked when you try to print the object.

System.out.println(myObject);  // invokes myObject.toString()

This method is defined in the Object class (the superclass of all Java objects). The Object.toString() method returns a fairly ugly looking string, composed of the name of the class, an @ symbol and the hashcode of the object in hexadecimal. The code for this looks like:

// Code of Object.toString()
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

A result such as com.foo.MyType@2f92e0f4 can therefore be explained as:

  • com.foo.MyType - the name of the class, i.e. the class is MyType in the package com.foo.
  • @ - joins the string together
  • 2f92e0f4 the hashcode of the object.

The name of array classes look a little different, which is explained well in the Javadocs for Class.getName(). For instance, [Ljava.lang.String means:

  • [ - an single-dimensional array (as opposed to [[ or [[[ etc.)
  • L - the array contains a class or interface
  • java.lang.String - the type of objects in the array


Customizing the Output

To print something different when you call System.out.println(myObject), you must override the toString() method in your own class. Here's a simple example:

public class Person {

private String name;

// constructors and other methods omitted

@Override
public String toString() {
return name;
}
}

Now if we print a Person, we see their name rather than com.foo.Person@12345678.

Bear in mind that toString() is just one way for an object to be converted to a string. Typically this output should fully describe your object in a clear and concise manner. A better toString() for our Person class might be:

@Override
public String toString() {
return getClass().getSimpleName() + "[name=" + name + "]";
}

Which would print, e.g., Person[name=Henry]. That's a really useful piece of data for debugging/testing.

If you want to focus on just one aspect of your object or include a lot of jazzy formatting, you might be better to define a separate method instead, e.g. String toElegantReport() {...}.



Auto-generating the Output

Many IDEs offer support for auto-generating a toString() method, based on the fields in the class. See docs for Eclipse and IntelliJ, for example.

Several popular Java libraries offer this feature as well. Some examples include:

  • ToStringBuilder from Apache Commons Lang

  • MoreObjects.ToStringHelper from Google Guava

  • @ToString annotation from Project Lombok



Printing groups of objects

So you've created a nice toString() for your class. What happens if that class is placed into an array or a collection?

Arrays

If you have an array of objects, you can call Arrays.toString() to produce a simple representation of the contents of the array. For instance, consider this array of Person objects:

Person[] people = { new Person("Fred"), new Person("Mike") };
System.out.println(Arrays.toString(people));

// Prints: [Fred, Mike]

Note: this is a call to a static method called toString() in the Arrays class, which is different to what we've been discussing above.

If you have a multi-dimensional array, you can use Arrays.deepToString() to achieve the same sort of output.

Collections

Most collections will produce a pretty output based on calling .toString() on every element.

List<Person> people = new ArrayList<>();
people.add(new Person("Alice"));
people.add(new Person("Bob"));
System.out.println(people);

// Prints [Alice, Bob]

So you just need to ensure your list elements define a nice toString() as discussed above.

Java: toString method printing the hash code instead of inOrder traversal

I think you should implement toString() method in your Student pojo.
Currently it is printing the object reference as per java notation

printing a toString() method output in a test class

Your WordPuzzleGenerator class does not override Object's toString. Instead it contains a static toString method with a different signature.

You need a method of this signature in your WordPuzzleGenerator class :

@Override
public String toString()
{
...
}

After taking another look, it appers your WordPuzzleGenerator has only static methods and no instance members, so it's unclear what you expect toString to return, or in other words - it's not clear what System.out.print(puzzle); is expected to print.

EDIT:

If you want toString() to print the Lists created in your constructor, you should make them instance members :

ArrayList<String> puzzleListY;
ArrayList<String> puzzleListX;
public WordPuzzleGenerator(int size) throws FileNotFoundException {
puzzleListY = new ArrayList<String>();
puzzleListX = new ArrayList<String>();
...
}

Then you can override toString like this :

@Override
public String toString()
{
return WordPuzzleGenerator.toString (puzzleListX,puzzleListY);
}

Arraylist output is not coming out as intended

You can use a for-each loop to print the contents of your list like this :
Note : you have to override toString() of your ToDo class and use this

   public static void main(String[] args) {
List<String> ls = new ArrayList<String>(); // use ToDo instead of String here
ls.add("a");
ls.add("b");
ls.add("c");
for (String s : ls) {
System.out.println(s);
}
}

O/P

a
b
c

override toString() of Todo class like this :

@Override
public String toString() {
return detail + "," + importance ; // add other fields if you want

}

Java toString printing error with a linkedlist using objects

Based on your latest code snippet:

        System.out.print(animal.toString());

...should be

        System.out.print(temp.animal.toString());

As animal is an instance variable of LinkNode, not PetList



Related Topics



Leave a reply



Submit