Generics5

Mostly migrating existing code from raw to proper generic types. Also using enhanced for loop to make the code more readable and removing some unnecessary null checks, redundant imports etc (see comments)