繁体   English   中英

在以对象为值的Java哈希表中,如何返回对象值?

[英]In a Java hashtable with objects as values, how do I return the object values?

这是我的示例代码。 这会打印出“ {test = theClass @ 7096985e}”,但我需要它来为我提供类型和范围的值。 我已经尝试了几件事-任何方向都很棒。 谢谢!

import java.util.*;

class theClass {
    String type;
    String scope;

    public theClass(String string1, String string2) {
        type = string1; scope = string2;
    }

}

public class Sandbox {

    public static void main(String[] args){
        Hashtable<String, theClass> theTable = new Hashtable<String, theClass>();
        theClass object = new theClass("int", "global");
        theTable.put("test", object);

        System.out.println(theTable.toString());

    }
}

只需在您的类中重写toString方法。

class theClass{
    String type;
    String scope;

    public theClass(String string1, String string2)
    {
        type = string1; scope = string2;
    }

    @Override
    public String toString(){
      return type+" "+scope;
    }

}

将方法toString()添加到您的theClass {}中,例如

@Override
public String toString() {
    return "theClass {type=" + type+", scope= "+scope+"};
}

您需要重写类中Object类提供的toString()方法的默认实现。

@Override
public String toString() {
   return "type=" + type+", scope= "+scope;
}

System.out.println()使用String.valueOf()方法来打印对象,该方法在对象上使用toString() 如果尚未在类中重写toString()方法,则它将调用Object类提供的默认实现,即:

Object类的toString方法返回一个字符串,该字符串包括该对象是其实例的类的名称,符号字符“ @”以及该对象的哈希码的无符号十六进制表示形式。 换句话说,此方法返回的字符串等于:

getClass()。getName()+'@'+ Integer.toHexString(hashCode())

因此,您会得到这样的输出。

您的代码正常工作。 您确实可以从哈希表中获取对象。 您对对象的字符串表示感到困惑。

要显示内部数据,您必须重写public String toString()方法的默认实现。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM