0

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

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

我不知道我是否将 ok 转换为 Object,或者第一行“Object 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;
}
}

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

4

2 回答 2

1

您在行内编写的代码存在很大问题

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

        }
    }
于 2015-05-28T06:21:19.200 回答
0

请注意,该values()方法返回值对象的集合,这里是字符串的集合。您不能将此转换为 IntPair,我很惊讶您的尝试没有导致编译器错误。

于 2015-01-17T02:16:04.723 回答