how-to

Generic

How use generic with "ArrayList"

This example shows how use generic with java.util.ArrayList.

STEP 1 - Prepare some class for storing -> "Person" class here

This is easy class for storing information about person.

package test;

public class Person {
          
  public Person( String name ) { 
    this.name = name; 
  }
 
  String name;

}

STEP 2 - Create "ArrayList" for storing "Person" classes

Now create list and add three Person class type items.

ArrayList persons = new ArrayList();
    
persons.add( new Person( "John" ) );
persons.add( new Person( "Amelia" ) );
    
Person p = new Person( "Frank" );
persons.add( p );
    
System.out.print( "Count: " + persons.size() );

The output from this example is:

Count: 3