import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class mainClass
{
static Scanner keyboard = new Scanner(System.in);
static HashMap <Integer[], String> hMap;
public static void createAHashMap()
{
System.out.print("Express the initial capacity: ");
int initialCapacity = keyboard.nextInt();
System.out.print("Express the load factor: ");
float loadFactor = keyboard.nextFloat();
hMap = new HashMap <Integer[], String> (initialCapacity, loadFactor);
}
public static void insertProductInformations()
{
Integer values[] = new Integer[3];
System.out.print("\nEnter product's barcode number: ");
values[0] = keyboard.nextInt();
System.out.print("Enter product's name: ");
String productName = keyboard.next();
System.out.print("Enter product's amount: ");
values[1] = keyboard.nextInt();
System.out.print("Enter product's price: ");
values[2] = keyboard.nextInt();
hMap.put(values, productName);
}
public static void displayList()
{
Set set = hMap.entrySet();
Iterator iterator = set.iterator();
System.out.println("\nBarcode Number\tProduct Amount\tProduct Price\tProduct Name");
while (iterator.hasNext())
{
Map.Entry mEntry = (Map.Entry) iterator.next();
System.out.print(mEntry.getKey() + "\t\t" + mEntry.getValue() + "\n");
}
}
public static void main(String[] args)
{
createAHashMap();
System.out.print("\nEnter to add product '1'\n");
System.out.print("Enter to display products '2'\n");
System.out.print("Enter your choice: ");
int entry = keyboard.nextInt();
while (entry != -99)
{
if (entry == 1)
{
insertProductInformations();
}
if (entry == 2)
{
displayList();
}
System.out.print("\nExpress your new choice (Exit: -99): ");
entry = keyboard.nextInt();
}
}
}
嗨!
我创建了一个哈希映射,其中包含超市中的产品信息。但是,我无法正确显示我的键值(这是一个数组)。它向我展示了除产品名称之外的无关紧要的东西。我怎么能纠正这个?
答案 0 :(得分:5)
static HashMap <Integer[], String> hMap;
数组不适合作为HashMap
中的键,因为具有完全相同元素的两个不同数组实例将被视为不同的键。这种行为是因为数组不会覆盖Object
的{{1}}方法,因此只有equals
和arr1
两个数组才相等{ {1}}。
打印钥匙不是您的主要问题。使用arr2
打印数组键可以轻松解决这个问题。
我建议您将arr1==arr2
更改为Arrays.toString
。
答案 1 :(得分:1)
我同意Eran的回答,你不应该选择你的密钥作为整数数组,但我认为你的显示问题不会用Arrays.toString完全解决,因为它会以指定的格式给出数组而不是在你需要的那个。您需要根据您的要求明确格式化数据。以上示例的显示示例修改可以是: -
public static void displayList()
{
Set set = hMap.entrySet();
Iterator iterator = set.iterator();
System.out.println("\nBarcode Number\tProduct Amount\tProduct Price\tProduct Name");
while (iterator.hasNext())
{
Map.Entry mEntry = (Map.Entry) iterator.next();
Integer[] values = (Integer[]) mEntry.getKey();
System.out.print(values[0] + "\t" + values[1] + "\t" + values[2] + "\t" + mEntry.getValue() + "\n");
}
}