You can use a Map to associate one key with one value.
In the code below, I use a Map that stores keys as integers and values as Strings.
Map<Integer, String> pageMap = new HashMap<>();
// inserting data
pageMap.put( 25, "Front Page" );
pageMap.put( 50, "Contents" );
pageMap.put( 75, "Index" );
// getting data
// will print Front Page
System.out.println( pageMap.get( 25 ) );
To iterate over a Map, i.e., to see what it have stored, you can do something like this:
for ( Map.Entry<Integer, String> e : pageMap.entrySet() ) {
System.out.printf( "%d -> %s\n", e.getKey(), e.getValue() );
}
If you need to preserve the insertion order, you will need to use a Linked implementation of the Map interface, like a LinkedHashMap. For example:
Map<Integer, String> pageMap = new LinkedHashMap<>();
When you iterate over this map, all the data will be presented in the insertion order, since it will preserve this order. For the HashMap presented above, the order will be dependant of how the HashMap will store the data (based on the hashCode of the key objects).
So, use a HashMap if you don't care about the order of the inserted data. Use an LinkedHashMap if you want to preserve the insertion order. There data will be stored. There are lots of different implementations for the Map interface. These implementations, for Java 7, can be found here https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Specifically for your problem, you will have something like:
int[] pageNumbers = {1, 25, 3};
Map<Integer, String> pageMap = new HashMap<>();
// inserting data
pageMap.put( 25, "Front Page" );
pageMap.put( 50, "Contents" );
pageMap.put( 75, "Index" );
for ( int page : pageNumbers ) {
String pageTitle = pageMap.get( page );
if ( pageTitle != null ) {
System.out.printf( "The title of the page %d is %s\n", page, pageTitle );
} else {
System.out.printf( "There is not a page title for the page %d\n", page );
}
}
As already said, you can also create an specialized class to group this data (page number with title or any other thing), stores it in a List and them iterate over this list to find the page you want, but for your problem, at least for me, it seems to be a better aprroach to use an Map.
Map. Also, do you mean page 2 was contents and page 3 was index?Mapwhich realizes pairs like(1 -> 25),(2 -> 50)etc. or use a dedicatedPairclass which holds both values and then use something likePair[]orList<Pair>.