【问题标题】:How to add custom java object to HashTable如何将自定义 java 对象添加到 HashTable
【发布时间】:2012-12-01 16:57:44
【问题描述】:

我有一个名为 Items 的类,其中一些数据如下:

class Items {
    public String item1 ;
    public String item2;
    public int item3;
}

我有另一个 Java 类为这个 Items 类设置值,如下所示:

Items tempItems1 = new Items();
tempItems1 .item1  = "a";
tempItems1 .item2  = "b";
tempItems1 .item3  = 1;

Items tempItems2 = new Items();
tempItems2 .item1  = "aa";
tempItems2 .item2  = "bb";
tempItems2 .item3  = 11;

现在的问题是我需要将这两个对象 (tempItems1,tempItems2) 添加到 HashTable 中,这样我就可以遍历 HashTable 来获取它的值。

我按如下方式创建了 HashTable,但找不到一种方法可以添加上述每个 Java 对象并遍历它。

HashTable<String,Items> custom = new HashTable<String,Items>();

谁能帮我解决这个问题?

【问题讨论】:

标签: java collections hashmap hashtable


【解决方案1】:

添加

custom.put("string_key1", tempItems1);
custom.put("string_key2", tempItems2);

遍历

for (Map.Entry<String, Items> entry : custom.entrySet()) {
    // entry.getKey()
    // entry.getValue()
}

【讨论】:

  • 嗨,我需要以这样一种方式进行遍历,即我需要提供密钥以获取以下值: entry.getKey 我应该作为 item1 和 entry.getvalue() 获取它的值“一个”
  • @user1276092 看来您对 Java 本身有问题。如果你有 Items 对象,你不能通过键访问成员变量;将它们设为私有并改用吸气剂。它不是 HashAnything,只是一个普通对象
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多