The two front students are wearing the same color hats, this is the only way all of the students could know what color hat they were wearing.
Explanation:
Call the colors A, B and C
The students in line have these colors: ABCC
First student sees "BCC" (two colors and a duplicate) so says "A"
2nd student sees "CC", so knows he is "B"
3rd student, using logic that the two previous students must have seen duplicates surmises he has a duplicate of the last remaining color and says "C"
4th student applies similar logic and says "C"