The list Interface

A good practice of using List is to use Generics instead of non-generics code. The following code snippet is non-generics and requires casting:

Use generics, the code does not require casting:

Code that uses generics has some benefits over non-generic code:

  • Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. This can avoid runtime errors.
  • Elimination of casting.

ArrayList is a common used implementations of List . The example bellow illustrate a list of object Human:

Human Class

Test Class

Run The Application

Right click to the ArrayListDemo class; select Run As -> Java Application.

Output

The other way to iterate the list for same result: