如何为自定义类创建println / print方法 [英] How to create a println/print method for a custom class
问题描述
我正在Java上开展一个项目,要求我制作一些容器类,如果你愿意的话。以下是一个简单版本:
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.)
我的问题是这样的:
当用一个方法调用println方法时ArrayList作为参数,例如:
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自动知道如何正确打印ArrayList的每个节点或元素。
Java automatically knows how to print each 'node' or element of the ArrayList correctly.
有没有办法写一个方法来让println方法正确打印我的Pair类?
推荐答案
您需要覆盖 toString
方法并返回所需内容的字符串表示形式。
You will need to override the toString
method and return a string representation of what you want.
例如:
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();
}
}
您可以执行以下操作:
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);
}
这篇关于如何为自定义类创建println / print方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!