简体   繁体   English

使用toString从哈希表获取字符串表示形式

[英]Getting string representations from a hashtable using a toString

Just wondering what the best way to represent Strings are from Hash tables, I figured you would use an iterator somehow in a toString method but wasn't sure. 我只是想知道从哈希表中表示字符串的最佳方法是什么,我想您会以某种方式在toString方法中使用迭代器,但不确定。

It should look something like the following 它看起来应该像下面这样

{5/10 = 3/9}
to
{true@5/10}@3/9

So far I have ( i know this doesn't use an iterator, since i wasn't really sure how to use it in this regard) 到目前为止,我已经知道了(我知道这不会使用迭代器,因为我不确定这方面如何使用它)

@Override
public String toString() {

    for (Map.Entry<BigFraction, BigFraction> entry : knowledgeD.entrySet()) {
        BigFraction key = entry.getKey();
        BigFraction value = entry.getValue();

where bigfraction is just a fraction datatype, replace it with whatever you want 在bigfraction只是分数数据类型的情况下,将其替换为所需的任何内容

Any help would be much appreciated 任何帮助将非常感激

the following may work, I believe 我相信以下可能有效

@Override
public String toString()
{
    final StringBuilder builder = new StringBuilder();
    for (final Map.Entry<String, String> entry : myTable.entrySet())
    {
        builder.append(entry.getKey());
        builder.append("=>");
        builder.append(entry.getValue());
        builder.append("\n");
    }

    return builder.toString();
}

if you want to see exact toString() representation, you can open the HashTable class and have a look at the toString() method. 如果要查看确切的toString()表示形式,可以打开HashTable类并查看toString()方法。
This is directly from JDK, 这直接来自JDK,

public synchronized String toString() {
    int max = size() - 1;
    if (max == -1)
        return "{}";

    StringBuilder sb = new StringBuilder();
    Iterator<Map.Entry<K,V>> it = entrySet().iterator();

    sb.append('{');
    for (int i = 0; ; i++) {
        Map.Entry<K,V> e = it.next();
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key   == this ? "(this Map)" : key.toString());
        sb.append('=');
        sb.append(value == this ? "(this Map)" : value.toString());

        if (i == max)
        return sb.append('}').toString();
        sb.append(", ");
    }
    }

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

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