How to create a println/print method for a custom class

前端 未结 6 1385
猫巷女王i
猫巷女王i 2020-12-01 19:23

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{

            


        
6条回答
  •  情书的邮戳
    2020-12-01 19:46

    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 pairs = new ArrayList();
    pairs.Add(new Pair("pair1key", "pair1value"));
    pairs.Add(new Pair("pair2key", "pair2value"));
    
    for (Pair p : pairs) {
        System.out.println(p);
    }
    

提交回复
热议问题