gpt4 book ai didi

Java 通过 HashMap 从 Object[][] 返回 int

转载 作者:行者123 更新时间:2023-11-30 04:16:08 25 4
gpt4 key购买 nike

我有一个属于索引的问题。我在一个单独的类中创建了一个 HashMap,以获取键的数据库和键的坐标。

public class Reference_Map {

private static HashMap<String, Object[][]> map;

public HashMap<String, Object[][]> getMap() {
return map;
}

public void setMap() {
map = new HashMap<String, Object[][]>();
map.put("A1", new Object [0][0]); map.put("A2", new Object [0][1]);
map.put("A3", new Object [0][2]);
map.put("B1", new Object [1][0]); map.put("B2", new Object [1][1]); map.put("B3", new Object [1][2]);
map.put("C1", new Object [2][0]); map.put("C2", new Object [2][1]); map.put("C3", new Object [2][2]);

这只是 map 的一小段,还有更多条目,从 A 到 P,从 1 到 24(A1 到 P24)。我决定这样做是因为我想获取访问 JTable 的键的坐标。我的意图是使用表的“setValueAt”函数,但似乎需要 (Object o, int row, int col) 才能正确。所以我的问题是,如何以某种方式获取键的坐标,我可以使用它来为表设置值?或者,如果确实不能这样完成,我如何以可以使用上述功能的方式存储我的数据库?

我尝试过的一些示例:

Reference_Map rm = new Reference_Map();
for (String s: rm.getMap().keySet()) {
if (s.equals(ID)) {
this.table1.setValueAt(result_short, rm.getMap().get(ID));
}
}

ID 是一个字符串,其中包含映射的未知键。 result_short 是一个应该写入 Jtable(私有(private) JTable table1)的字符串。表本身的构造如下:

    String[] columnNames = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"};
this.data = new Object[16][24];
this.table1 = new JTable(this.data, columnNames);

希望您能帮助我,感谢您的尝试

最佳答案

在我看来,问题出在您选择在 map 中存储坐标的方式。

如果你想存储位置 (3,4) - 存储 new Object[3][4] 它不会帮助你。当您调用 rm.getMap().get(ID) 时,您不会收到位置信息。

要更改此设置,您需要另一个类,我们将其称为“位置”。您更改向 map 引入坐标的方式:

class Position{
int x;
int y;
Position(int x, int y) {
this.x=x;
this.y=y;
}
}
map.put("C2", new Position(2,1));

这样,rm.getMap().get(ID)就会给你一个Position对象(Position p)。您将能够继续使用它:

Position p = rm.getMap().get(ID);
this.table1.setValueAt(result_short, p.getX(), p.getY());

这样你就会尊重:(Object o, int row, int col)。

我希望我理解了这个问题。

编辑

要创建新实例new Position(2,1),您需要提供一个构造函数。我编辑了上面的类定义。

关于Java 通过 HashMap 从 Object[][] 返回 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18332523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com