[Java]Generics

William Parker·2022년 11월 9일
0
post-thumbnail
  • What is Generics?

    • It refers to a function that performs type checking at compile time on a method or collection class that handles various types of objects.
  • Why use generics?

    • Stability is improved because the object type is checked at compile time.
      (Because it prevents objects of unintended types from being saved and prevents incorrect casts!)
  • type of generics

public class Class name<T> {...}
public interface Inferface name<T> {...}
  • Commonly used type factor abbreviations
<T> == Type
<E> == Element
<K> == Key
<V> == Value
<N> == Number
<R> == Result
  • Example using generics
    • We were already using Generics. The best use of generics is in Collections (or other data structures that implement Collection ). Let's take a look at the Collection class to see how generics are used.

Collection.java

public interface Collection<E> extends Iterable<E> {
	int size();
	boolean isEmpty();
	Iterator<E> iterator();
	boolean add(E e);
	<T> T[] toArray(T[] a);
	boolean containsAll(Collection<?> c);
	boolean addAll(Collection<? extends E> c);
}

List.java

public interface Collection<E> extends Iterable<E> {
	int size();
	boolean isEmpty();
	Iterator<E> iterator();
	boolean add(E e);
	<T> T[] toArray(T[] a);
	boolean containsAll(Collection<?> c);
	boolean addAll(Collection<? extends E> c);
}

ArrayList.java

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable 
{
	public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }
    public E get(int index) {
        rangeCheck(index);

        return elementData(index);
    }
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
}

Generics make it easy to handle cases where the behavior is the same but only the class type needs to be changed. With generics, you can write flexible programs while ensuring type stability, a characteristic of compiled languages.

profile
Developer who does not give up and keeps on going.

0개의 댓글