繁体   English   中英

检查HashMap的值<Object,String>

[英]Check values of HashMap <Object,String>

我有一个IntPair类,可以从中使用两个方法:“ getFirst()”和“ getSecond()”。 目前,在使用此方法时,我想检查“ hashMap j”是否包含特定值,然后执行操作。 我认为这些方面存在问题:

Object obj = j.values();
t.moveCursor(((IntPair)obj).getFirst(), ((IntPair)obj).getSecond());

我不知道是否要对对象进行转换,或者是否应将第一行“对象obj = j.values()”替换为另一个方法调用。 我在j.containsValue(“ 0”)之后使用System.out.print(“ Message”)进行了测试,然后得到了返回的消息。

这是我尝试使其工作的方法的一部分。

public static HashMap<IntPair, String> j = new HashMap<>();

j.put(new IntPair(firstInt, secondInt), value);
if (j.containsValue("0"))
{
Object obj = j.values();
t.moveCursor(((IntPair)obj).getFirst(), ((IntPair)obj).getSecond());
t.putCharacter('x');
}
else if (j.containsValue("1"))
{
Object obj = j.values();
t.moveCursor(((IntPair)obj).getFirst(), ((IntPair)obj).getSecond());
t.putCharacter('v');
}

配对班:

public class IntPair {
private final int first;
private final int second;

public IntPair(int first, int second) {
    this.first = first;
    this.second = second;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 89 * hash + this.first;
    hash = 89 * hash + this.second;
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final IntPair other = (IntPair) obj;
    if (this.first != other.first) {
        return false;
    }
    if (this.second != other.second) {
        return false;
    }
    return true;
}

public int getFirst() {
    return first;
}

public int getSecond() {
    return second;
}
}

任何帮助将非常感激。 谢谢!

您在线编写的代码有一个大问题

t.moveCursor(((IntPair)obj).getFirst(), ((IntPair)obj).getSecond());

表达方式

((IntPair)obj).getFirst() 

不会返回getFirst值,因为obj在这里不是IntPair类型,但是obj是由以下元素返回的IntPair元素的集合

Object obj = j.values();

因此,您必须从此集合中检索IntPair元素,然后才能阅读getFirst()我编写了一个小程序来说明我的观点

public static HashMap<IntPair, String> j = new HashMap<IntPair, String>();

    public static void main(String[] args) {
        j.put(new IntPair(2, 3), "0");
        if (j.containsValue("0")) {
            Set<Entry<IntPair, String>> pairs = j.entrySet();
            Iterator<Entry<IntPair, String>> it = pairs.iterator();
            Entry e;
            while (it.hasNext()) {
                e = it.next();
                if (e.getValue().equals("0")) {
                    IntPair resultObj = (IntPair) e.getKey();
                }
            }

        }
    }

请注意, values()方法返回values对象的Collection,这里是String的Collection。 您不能将其强制转换为IntPair,而您的尝试并未引起编译器错误,我感到很惊讶。

暂无
暂无

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

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