Collection interface

PHOTO EMBED

Sun Dec 25 2022 21:56:15 GMT+0000 (Coordinated Universal Time)

Saved by @prettyleka #java #generics

//the Collection interface provides a generic, general-purpose API when our program needs a collection of elements and doesn’t care about what type of collection it is.
//Implementing classes may implement collections methods and add restrictions to them, like a Set does to only contain unique elements. Also, implementing classes or extending interfaces do not need to implement all methods and instead will throw an UnsupportOperationException when a Collection method is not implemented.
//We’ve seen add() and remove() be used but some other methods Collection defines are:
//addAll() - receives a Collection argument and adds all the elements.
//isEmpty() - return true if the collection is empty, false otherwise.
//iterator() - returns an Iterator over the collection.
//size() - returns the number of elements in the collection.
//stream() - returns a Stream over the elements in the collection.
//toArray() - returns an array with all elements in the collection.

Collection<Integer> collection = new ArrayList<>();
collection.add(4);
collection.add(8);
 
boolean isEmpty = collection.isEmpty(); // false
int collectionSize = collection.size(); // 2
 
Integer[] collectionArray = collection.toArray(new Integer[0]);

private static <T> void printCollection(Collection<T> collection) {
    for(T item: collection){
      System.out.println(item);}
  }
content_copyCOPY