I'm working in Java on a project that requires me to make a few 'container' classes, if you will. Here is a simple version of one:
public class Pair{
Object KEY;
Object VALUE;
public Pair(Object k, Object v)
{
KEY = k;
VALUE = v;
}
public Object getKey()
{ return KEY; }
public Object getValue()
{ return VALUE; }
}
(Please note, this is severely simplified and I am using proper set/get methods in the final version.)
My question is this:
When calling the println method with an ArrayList as the parameter, for example:
ArrayList<String> arr = new ArrayList<String>();
arr.add("one");
arr.add("two");
System.out.println(arr);
Java automatically knows how to print each 'node' or element of the ArrayList correctly.
Is there a way to write a method to allow the println method to correctly print my Pair class?
Prints:
123 This St.
Big Tuna, Texas
456 That St.
Phoenix, Arizona
You'll have to define a
toString()
method. It's called automatically bySystem.out.println(Object o)
. TheArrayList
class has such an overriddentoString()
method that provides a nicely formatted representation.Basically, overriding Object.toString with your own definition is all that is required.
You will need to override the
toString
method and return a string representation of what you want.So for example:
Than you can do the following:
You need to override
toString()
:You could extend
ArrayList
and override thetoString()
method:But this is overkill. I would just write a print utility method.
You can override the
toString()
method of your custom class and print whatever information you want.