【发布时间】:2013-11-23 12:24:12
【问题描述】:
我在整理此代码时遇到了一些麻烦,该代码位于哈希图中 - 我还需要一些帮助来整理一个类似的双倍代码集(价格)。谢谢。
@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;
}
}
});
}
}
}
}
【问题讨论】:
-
您能否请格式化您的代码。当我看到
});}}时,我的大脑很痛(感谢@mKorbel 的编辑)。具体来说,您的代码有什么问题? -
请在您的班级中实现
Comparable:class Sellable implements Comparable<Sellable>{ @Override public int compareTo(Sellable other){ } } -
排序与排序不一样
-
我试图弄清楚如何对硬编码到我的库存对象中的所有元素进行排序。抱歉,如果您的大脑受伤了-我的大脑也因试图弄清楚而受伤……
-
@Mr. Polywhirl --> Sellable 是一个接口,而不是一个类,不幸的是......
标签: java sorting methods arraylist hashmap