How to create a println/print method for a custom class
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?
Solution 1:
You will need to override the toString
method and return a string representation of what you want.
So for example:
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;
}
public String toString() {
return "Key: " + getKey() + ", Value: " + getValue();
}
}
Than you can do the following:
List<Pair> pairs = new ArrayList<Pair>();
pairs.Add(new Pair("pair1key", "pair1value"));
pairs.Add(new Pair("pair2key", "pair2value"));
for (Pair p : pairs) {
System.out.println(p);
}
Solution 2:
You need to override toString()
:
public class Pair
{
KeyObject key;
ValueObject value;
public Pair(KeyObject k, ValueObject v)
{
key = k;
vale = v;
}
// ...
@Override
public String toString()
{
return "Key: " + key.getKey() + " - Value: " + value.getValue();
}
}
Solution 3:
You can override the toString()
method of your custom class and print whatever information you want.
@Override
public String toString() {
return .....;
}
Solution 4:
You could extend ArrayList
and override the toString()
method:
public class MyArrayList<T> extends ArrayList<T> {
@Override
public String toString() {
// format your print here...
}
}
But this is overkill. I would just write a print utility method.
public class MyUtils {
public String toString( ArrayList<? extends Object> ) {
// format your print here;
}
}