如何为自定义类创建 println/print 方法 [英] How to create a println/print method for a custom class

查看:43
本文介绍了如何为自定义类创建 println/print 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您愿意,我正在使用 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; }
}

(请注意,这被大大简化了,我在最终版本中使用了正确的 set/get 方法.)

(Please note, this is severely simplified and I am using proper set/get methods in the final version.)

我的问题是:

以ArrayList为参数调用println方法时,例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆