如何 return HashMap 对象字段

How to return HashMap object fields

我目前在假期中有以下 HashMap class。

假期Class:

HashMap <String, Location> holidays = new HashMap<String, Location>();

这将创建位置实例 class,以允许显示更多字段。

位置class:

public class Location {
private String locationName;
private String locationDesc;
private double price;
private int quantity;

public Location(String locationName, String locationDesc, double price) {
    this.locationName = locationName;
    this.locationDesc = locationDesc;
    this.price = price; 
    quantity = 0;
}

public String toString() {
    return (locationName + " | " + "£" + price);
}
public double getPrice() { return price; }
public String getLocationName() { return locationName; }
public String getLocationDesc() { return locationDesc; }
public int getQuantity() { return quantity; }
}

在我的 GUI 中 class 我只使用 .get HashMap 方法,这将 return toString。 例如

图形界面class

private Holiday holiday;
...
return holiday.holidays.get(--HashMap key here--);

这将 return toString,即位置名称和价格。

不过。我还想在其他地方打印出 HashMap,但使用 returning 不同的字段。例如 returning 描述和数量以及 locationName 和价格。我将如何去做这件事?或者我如何 return Location class 中的各个字段,它是 HashMap 中的一个实例。

设法做到这一点。但需要以下方面的帮助


第二次编辑:

我在我的位置 class 中有一个设置数量的方法来设置每个假期的预订量。但是当使用;

for (Location location : holiday.holidays.values()) {
location.setQuantity(Integer.parseInt(textFieldQuantity.getText()));
}

当为每个位置设置不同的数量时,这会将所有假期更改为相同的数量。我该如何解决这个问题?

holidays.get(key) 的结果应该是 Location 类型的对象。如果你直接打印对象,就像在 System.out.println(holidays.get(key)) 中一样,它会像你说的那样打印 toString() 的结果。但是由于您已经拥有该对象并可以访问其字段,因此您可以准确地打印出您想要的内容。

像这样的东西应该可以工作:

Location location = holidays.get(key);
System.out.println(location.getlocationDesc() + " | " + location.getQuantity());

关于你的第二个问题:

如果您只需要打印存储在地图中的所有值,我认为直接在地图值上迭代会更清晰、更快速:

for (Location location : holiday.holidays.values()) {
    System.out.println(location.getlocationDesc() + " | " + location.getQuantity());
}

第三题:

请注意,您的代码并未只为一个位置设置数量。它遍历所有位置,将每个数量设置为相同的值,由 textFieldQuantity.getText().

定义

如果要修改特定位置,需要使用get()从地图中检索它:

Location location = holiday.holidays.get(key);
location.setQuantity(Integer.parseInt(textFieldQuantity.getText()));

为什么不尝试这样的事情:

private Location location = holiday.holidays.get(--HashMap key here--);

// Create a string with the variables

然后是 return 字符串。

this will return the toString, which is locationName and price

没有。它将 return Location 的一个实例。所以你所要做的就是

Location location = holiday.holidays.get("some key");
double price = location.getPrice();
String locationName = location.getLocationName();

注意

  • 您不应使用 public 字段。所以应该改为location.getHolidays().get("some key")。或者甚至更好,封装 Map 并遵守 "don't talk to strangers" 规则,location.getHoliday("some key").
  • 您的 getter 应该命名为 getLocationName() 而不是 getlocationName() 以尊重 JavaBean 约定。或者甚至更好,因为这个方法是 Location class 的一部分,位置前缀是多余的,因此你应该简单地将它命名为 getName() (和 getDescription() 作为描述)