Actually, the accepted answer will take linear time per query. While a HashMap is still a better option (with constant amortized time), you can do better than linear time with arrays if you rearrange them so that postalCode is sorted. This allow you to perform O(log(n)) binary searches.
Example:
final int[] orderedPostCode = { 1000, 2000, 2300, 8500, 9000, 9200, 9300, 9700 };
final String[] orderedCities = { "Brussel", "Antwerpen", "Turnhout", "Kortrijk", "Gent", "Dendermonde", "Aalst", "Oudenaarde" };
final int code = Integer.parseInt(JOptionPane.showInputDialog("Give a postal code"));
final int codePos = Arrays.binarySearch(orderedPostCode, code);
if (codePos < 0) {
JOptionPane.showMessageDialog(null, "Postal code not found", "Error", JOptionPane.ERROR_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null, "City: " + orderedCities[codePos]);
}
This leads to a interesting follow up problem: How to sort an arbitrary set of postal codes and cities in the way needed for fast binary searches:
int[] postalCode = {9300,2000,1000,9200,9000,8500,9700,2300};
String[] city = {"Aalst","Antwerpen","Brussel","Dendermonde","Gent","Kortrijk","Oudenaarde","Turnhout"};
int[] orderedPostCode = Arrays.copyOf(postalCode, postalCode.length);
Arrays.sort(orderedPostCode);
String[] orderedCities = rearrangeCities(city, postalCode, orderedPostCode);
System.out.println(Arrays.toString(orderedPostCode));
System.out.println(Arrays.toString(orderedCities));
// Will print the arrays of the first example
And here is the rearrangeCities implementation O(n²):
private static String[] rearrangeCities(String[] cities, int[] postalCode, int[] orderedPostCode) {
final String[] orderedCities = new String[cities.length];
for (int newPos = 0; newPos < orderedPostCode.length; newPos++) {
final int curPostalCode = orderedPostCode[newPos];
for (int oldPos = 0; oldPos < postalCode.length; oldPos++) {
if (postalCode[oldPos] == curPostalCode) {
orderedCities[newPos] = cities[oldPos];
break;
}
}
}
return orderedCities;
}
Since your goal is to improve your knowledge of arrays in Java, I believe that these are good examples.
Map<Integer, String>.