Java 从LinkedHashMap获取对象值
因此,对于我的本地数据结构,我有以下内容Java 从LinkedHashMap获取对象值,java,android,Java,Android,因此,对于我的本地数据结构,我有以下内容 DataStructure ds = new DataStructure(); //Examples to put in the Data Structure "ds" ds.menu_item.put("Pizza", new DescItems("A Pizza",2.50,4)); ds.menu_item.put("Hot Dog", new DescItems("A yummy hot dog",3.50, 3));
DataStructure ds = new DataStructure();
//Examples to put in the Data Structure "ds"
ds.menu_item.put("Pizza", new DescItems("A Pizza",2.50,4));
ds.menu_item.put("Hot Dog", new DescItems("A yummy hot dog",3.50, 3));
ds.menu_item.put("Corn Dog", new DescItems("A corny dog",3.00));
ds.menu_item.put("Unknown Dish", new DescItems(3.25));
DataStructure类具有LinkedHashMap实现,因此
LinkedHashMap<String, DescItems> menu_item = new LinkedHashMap<String, DescItems>();
没有itemDescription和/或itemRating需要考虑其他构造函数
我正在尝试应用一种方法来检查一个值是否具有除0以外的itemRating(0表示没有评级)
但具体来说,我遇到了这个问题:
DescItems getC1 = (DescItems)ds.menu_item.get("Pizza");
System.out.println(getC1.toString());
仅打印参考信息,如DescItems@142D091
如何获取特定的对象变量而不是引用对象?您可以在
DescItems
类中重写toString()
方法。例如:
public class DescItems {
. . .
@Override
public String toString() {
// whatever you want here
return String.format("%1$s (price: $%2$.2f; rating: %3$f)",
itemDescription, itemPrice, itemRating);
}
}
toString()
的默认实现返回一个与您所看到的类似的对象标识字符串
另一种方法是打印所需的精确字段:
System.out.println(getC1.itemDescription);
您需要重写
DescItems
大概是这样的:
@Override
public String toString() {
return itemDescription + " " + itemPrice + currencySymbol + " (" + itemRating + ")";
}
只需重写toString()方法即可返回所需的文本
@Override
public String toString() {
return itemDescription + " " + itemPrice + currencySymbol + " (" + itemRating + ")";
}