简体   繁体   中英

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

Here is my sample code. This prints out "{test=theClass@7096985e}" but I need it to give me the values of type and scope. I have tried several things--any direction would be awesome. Thanks!

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());

    }
}

Just override the toString method in your class.

class theClass{
    String type;
    String scope;

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

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

}

Add a Method toString() to your theClass{} eg

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

You need to override the default implementation of toString() method provided by the Object class in your class.

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

System.out.println() uses String.valueOf() method to print objects , which uses the toString() on the object . If you haven't overridden the toString() method in your class then it will invoke the default implementation provided by the Object class , which says :

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

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

Hence you get such an output.

Your code works correctly. You indeed get your object from hash table. You are confused with the string representation of your object.

To show internal data you have to override default implementation of public String toString() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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