gpt4 book ai didi

java - 在 HashMap 中显示问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:49:56 25 4
gpt4 key购买 nike

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();
}
}
}

嗨!

我创建了一个包含超市产品信息的 HashMap 。但是,我无法正确显示我的键值(这是一个数组)。它向我显示了除产品名称外无关紧要的内容。我该如何纠正这个问题?

最佳答案

static HashMap <Integer[], String> hMap;

数组不适合作为 HashMap 中的键,因为具有完全相同元素的两个不同数组实例将被视为不同的键。此行为是由于数组不覆盖 Object 的事实造成的的 equals方法,所以两个数组 arr1arr2仅当 arr1==arr2 时才相等.

key 的打印不是您的主要问题。这可以通过使用 Arrays.toString 轻松解决。打印数组键。

我建议你改变你的HashMapHashMap<List<Integer>, String> .

关于java - 在 HashMap 中显示问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34478425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com