collections and generics

3 minute read

Published:

Java basics – collections and generics

Collections and generics

  • Collection: a container provided in java that can be used to store multiple data

  • Collection vs Array
    1. The length of the collection is variable, and the length of the array is immutable
    2. Arrays store elements of the same type, and collections store objects, which can be inconsistent
  • List interface

    1. an ordered collection

    2. Allow storage of duplicate elements

    3. There is index, you can use for loop to traverse

      Vector, ArrayList, LinkedList

  • Set interface

    1. Do not allow storage of duplicate elements

    2. Without an index, you cannot use a for loop to traverse

      TreeSet (unordered), HashSet (unordered), LinkedHashSet (ordered)

Collection

Defines the methods common to all single-column sets (there is no method with index)

  1. public boolean add(E e): add the given object to the current collection
  2. public void clear(): Clear all elements in the collection
  3. public boolean remove(E e): remove the given object from the collection
  4. public boolean contains(E e): Determine whether the set contains the given object
  5. public boolean isEmpty(): Determine whether the current collection is empty
  6. public int size(): returns the number of elements in the collection
  7. public Object[] toArray(): Store the elements in the collection into an array

Iterator

Used to access elements in Collection

  1. boolean hasNext(): If there are still elements to iterate, return true
  2. E next(): returns the next element of the iteration

Note: Iterator is an interface, you can get iterator through the iterator method in Collection

Collection<String> coll=new ArrayList<>();
//...
Iterator<String> it=coll.iterator();
while(it.hasNext()){
    String s=it.next();
    //...
}
  • Enhanced for loop: Iterator (JDK1.5+) is also used at the bottom to traverse collections or arrays

    All single-column collections can use enhanced for

    for (collection/array data type variable name: collection name/array name) {
        System.out.println(variable name);
    }
    

Generic

Generic: an unknown data type, when we don’t know what data type to use, we can use generics

  • Benefits of using generics
    1. Avoid the trouble of type conversion
    2. Raise the runtime exception to compile time
  • Definition and use of generics

    1. Define and use generic classes

      Modifier class class name <representing generic variable>{...}

      Such as:

       class ArrayList<E>{
           public boolean add(E e){......}
           ...
       }//definition
       ArrayList<Integer> arr=new ArrayList<>();//use
      
    2. Define and use generic methods

       Modifier <type> return value type method name (parameter list (using generics)) {
           Method body
       }
      

      Such as:

       public <M> void method(M m){
           ...
       }//definition
       //use
       method(10);
       method("abc");
      

      Note: what type is passed, generic type is what type

    3. Define and use generic interfaces

      Modifier interface class name <representing generic variables> {...}

      use:

      1. The implementation class determines the type
      2. Define an implementation class with generics
    4. Generic wildcards ? Represents any data type How to use:

      • Cannot create objects and use them only as method parameters
      • Advanced use of wildcards-restricted generics

        1. The upper limit of generics: type name <? extends class> object name; Can only receive this type and its subclasses
        2. The lower limit of generics: type name <? super class> object name; Can only receive the type and its parent