我是 Java 的新手,我正在处理数组。我有两个数组,想将它们链接起来,使第二个数组中的元素与第一个数组中的元素相对应。这样,我就可以在第一个数组中搜索一个元素,并在第二个数组中显示相应的值。
short[] Years = {2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012};
String[] Months = {"January", "February", "June", "January", "March", "June", "July", "August", "September", "March", "November", "March", "June"};
我正在尝试链接它,以便当我搜索 March 时,例如,它会显示 2004, 2009, 2011
List<String> results = new ArrayList<String>();
for (String s : months)
{
if(s.equals(term))
{
results.add(s);
}
}
if (results.size() > 0)
{
System.out.println("The month " + term + "appears " + results.size() + " times");
}
else
{
System.out.println("Your search for " + term + " did not return any results");
}
我有这个代码来显示一个月出现了多少次,我只需要它来打印出这之后的年份。
最佳答案
这是一个“关联数组”或“映射”。这是一个 Java 示例。
Map<String, String> userEmails = new HashMap<String, String>();
userEmails.put("Tony", "tony@metal.com");
userEmails.put("Ozzy", "ozzy@metal.com");
让我们找到 Ozzy 并打印他的电子邮件地址:
System.out.println(userEmails.get("Ozzy"));
Map是界面。它有操作“put”和“get”。 HashMap是“ map ”的一种流行实现,其中 map 键(用户名)具有唯一的哈希码。
关于java - 在 Java 中链接数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16096273/