我对主题有疑问,如何保存在HashMap中。我有2个ArrayList,在第一个ArrayList中,我有一些Pizzaname。在另一个ArrayList中,我有成分。我现在要定义一下,例如,“比萨香肠”具有萨拉米香肠,奶酪,西红柿和“比萨饼”的成分。然后,我想将其保存在HashMap中。
有人可以帮助我吗?
我有这个ArrayLists:
List<Pizza> pizzaEntries= new ArrayList<>();
List<Ingredients> ingredientsEntries= new ArrayList();
pizzaEntries.add(new Pizza("Salami",3.50);<-- 3.50=price
ingredientsEntries.add(new Ingredients("cheese",0.50);
ingredientsEntries.add(new Ingredients("Salami", 1.50);
ingredientsEntries.add(new Ingredients("Pickles", 0.50);
ingredientsEntries.add(new Ingredients("Thuna", 1.50);
现在我该如何定义Pizza Salami包含奶酪和Salami的成分
答案 0 :(得分:0)
import java.util.HashMap;
import java.util.Map;
class Pizza implements Comparable {
String name;
Pizza(String name){
this.name = name;
}
@Override
public int compareTo(Object o) {
if(((Pizza)o).name.equals(this.name)){
return 0;
}
return -1;
}
}
enum PizzaIngredient{
SALAMI,
HAM;
}
public class Test {
Map<Pizza, PizzaIngredient[]> map = new HashMap<>();
Map<String, PizzaIngredient[]> mapAlternative = new HashMap<>();
public Test(){
PizzaIngredient [] pizzaIngredients = {PizzaIngredient.SALAMI};
map.put(new Pizza("Salami"),pizzaIngredients);
mapAlternative.put("Salami", pizzaIngredients);
}
}
这将是我的解决方案之一。或者,您也可以不用HashMap使其变得简单,并使用其自己的一系列比萨配料使每个比萨变得独一无二p>
import java.util.Arrays;
class Pizza implements Comparable {
String name;
PizzaIngredient [] pizzaIngredients;
Pizza(String name, PizzaIngredient ... pizzaIngredients){
this.name = name;
this.pizzaIngredients = pizzaIngredients;
}
@Override
public int compareTo(Object o) {
if(Arrays.equals(((Pizza)o).pizzaIngredients, this.pizzaIngredients)){
return 0;
}
return -1;
}
}
enum PizzaIngredient{
SALAMI,
HAM;
}
public class Test {
public static void main(String[] args) {
Pizza salami = new Pizza("Salami", PizzaIngredient.HAM, PizzaIngredient.SALAMI);
}
}
答案 1 :(得分:0)
您可以在下面将“成分”定义为一个类:
<header>Header</header>
<main>
<div>Div</div>
</main>
然后在主类中,您可以创建披萨类型到配料的映射。
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Ingredients
{
private Map<String, Double> aIngredientTypeToCost = new HashMap<>();
public void put(String theType, Double theCost)
{
aIngredientTypeToCost.put(theType, theCost);
}
public Set<String> getAllIngredientsType()
{
return aIngredientTypeToCost.keySet();
}
}