I happen to read the following code segment from Thinking in Java

public class PetCount3 {
static class PetCounter
extends LinkedHashMap<Class<? extends Pet>,Integer> {
public PetCounter() {
super(MapData.map(LiteralPetCreator.allTypes, 0));
}
public void count(Pet pet) {
// Class.isInstance() eliminates instanceofs:
for(Map.Entry<Class<? extends Pet>,Integer> pair
: entrySet())
if(pair.getKey().isInstance(pet))
put(pair.getKey(), pair.getValue() + 1);
}
public String toString() {
StringBuilder result = new StringBuilder("{");
for(Map.Entry<Class<? extends Pet>,Integer> pair
: entrySet()) {
result.append(pair.getKey().getSimpleName());
result.append("=");
result.append(pair.getValue());
result.append(", ");
}
result.delete(result.length()-2, result.length());
result.append("}");
return result.toString();
}
}

I am quite confusing about the two specifc lines in the above code.

static class PetCounter
extends LinkedHashMap<Class<? extends Pet>,Integer>

What does LinkedHashMap<Class<? extends Pet>,Integer> mean here?

Similarily, it also has

for(Map.Entry<Class<? extends Pet>,Integer> pair
: entrySet())

How to understand the usage of <Class<? extends Pet>,Integer> and pair:entrySet() here?

They are Generics - a way of specifying what kind of Objects can be used for the keys and values of the map. Read all about it here:
http://download.oracle.com/javase/tutorial/java/generics/index.html

The for (xxx : yyy) syntax is the "enhanced for loop" yyy must be some kind of collection of xxx's, the loop sets xxx to the first element of yyy and executes the code in the loop, then the second etc.
eg

for (int num : someArrayOfInts){
   // etc
}

is equivalent to

for (i = 0; i<someArrayOfInts.length; i++) {
   int num = someArrayOfInts[i];
   // etc
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.