我在整理此代码时遇到了一些麻烦,该代码位于哈希图中 - 我还需要一些帮助来整理双(价格)的类似代码集。谢谢你。
@SuppressWarnings("unused")
public class Inventory {
Scanner in = new Scanner(System.in);
ArrayList<Sellable> groceries;
HashMap<String, Integer> stock;
public Inventory() {
groceries = new ArrayList<Sellable>();
stock = new HashMap<String, Integer>();
//HARDCODING...:
Sellable n1 = new Produce("Corn", 3, 5.00);
Sellable n2 = new Snack("Natural Popcorn Seeds", 2.50);
Sellable n3 = new Produce("Potatoes", 3, 5.00);
Sellable n4 = new Snack("Organic Potato Chips", 2.50);
Sellable n5 = new Produce("Apples", 5, 1.75);
Sellable n6 = new Snack("Apple Juice - 128 oz.", 3.50);
Sellable n7 = new Produce("Oranges", 5, 1.75);
Sellable n8 = new Snack("Orange Juice - 128 oz.", 3.50);
//ADD TO HASHMAP
groceries.add(n1);
groceries.add(n2);
groceries.add(n3);
groceries.add(n4);
groceries.add(n5);
groceries.add(n6);
groceries.add(n7);
groceries.add(n8);
//PUT UP FOR PRINTING
stock.put(n1.getName(), 50);
stock.put(n2.getName(), 100);
stock.put(n3.getName(), 50);
stock.put(n4.getName(), 100);
stock.put(n5.getName(), 50);
stock.put(n6.getName(), 100);
stock.put(n7.getName(), 50);
stock.put(n8.getName(), 100);
}
//Sorting Method 1
@SuppressWarnings("unchecked")
public void sortByName() {
groceries = new ArrayList<Sellable>();
stock = new HashMap<String, Integer>();
{
if (stock != null) {
List<Sellable> groceries = new ArrayList<Sellable>();
stock.addAll(((Entry<String, Integer>) stock).getValue(), groceries);
Collections.sort(groceries, new Comparator<Sellable>() {
public int compare(Sellable product1, Sellable product2) {
try {
Sellable choice1 = (Sellable) product1;
Sellable choice2 = (Sellable) product2;
//LESS THAN
if (choice1.getName().compareTo(choice2.getName()) < 0) {
return -1;
} //GREATER THAN
else if (choice1.getName().compareTo(choice2.getName()) > 0) {
return 1;
} //EQUALS
else {
return 0;
}
} catch (ClassCastException FAIL) {
return -2;
}
}
});
}
}
}
}