r123454321
r123454321

Reputation: 3403

Overriding toString() for one particular instance of a Multimap?

I have an instance of a ListMultimap (Guava) which is composed of nested HashMaps and rather complex objects -- is there any way to change the toString() for this instance to customize the console output when I print the HashMap? Or is the only way to make a new class which is an extension of the HashMap class, and rewrite the toString() method as follows:

class CustomizedListMultiMap extends ListMultiMap<myComplexDatatypeOne, myComplexDatatypeTwo> {
    // overwriting toString
    public String toString() {
        // my custom implementation
    }
}

Multimaps are instantiated as follows:

ListMultimap<datatypeOne, datatypeTwo> map = ArrayListMultimap.create();

so I don't think the first answer is applicable? (Thanks though.)

Upvotes: 1

Views: 728

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198023

I'm under the impression you have a ListMultimap<Foo, List<Bar>>, and you want to print it out in a format looking like {a=[1, 2, 3]} corresponding to the lengths of the List<Bar>s.

The simplest way to do that is probably

Multimaps.transformValues(multimap, new Function<List<Bar>, Integer>() {
   public Integer apply(List<Bar> list) {
     return list.size();
   }
}).toString();

Upvotes: 1

arshajii
arshajii

Reputation: 129497

How about an anonymous class:

Map<X, Y> map = new HashMap<X, Y>() {
    @Override
    public String toString() {
        // toString implementation here
    }
};

EDIT: Looks like you want to do this with a final class. I would instead suggest writing a separate static toString method and calling that instead, instead of somehow trying to add it to the class itself:

public static String mapToString(Map<X, Y> map) {
    // toString implementation here
} 

Upvotes: 4

lory105
lory105

Reputation: 6302

You have to override the toString() method in your custom class "customizedHashMap". You can not customize the toString() method only for one instance of your class.

I suggest you use class names with the first letter capitalized!

Upvotes: 0

Related Questions