DEV Community

FUNDAMENTOS JAVA
FUNDAMENTOS JAVA

Posted on

1

Convenção de Tipos Genéricos

A convenção de nomenclatura de tipos genéricos em Java segue algumas diretrizes comuns para tornar o código claro e consistente. Aqui estão algumas convenções padrão:

T: Tipo (geralmente usado quando há um único parâmetro genérico).

public interface List<T> {
    void add(T element);
    T get(int index);
}

Enter fullscreen mode Exit fullscreen mode

E: Elemento (geralmente usado em coleções).

public interface Collection<E> {
    void add(E element);
    E get(int index);
}
Enter fullscreen mode Exit fullscreen mode

K, V: Chave e Valor (geralmente usados em mapas).

public interface Map<K, V> {
    V put(K key, V value);
    V get(K key);
}
Enter fullscreen mode Exit fullscreen mode

N: Número (geralmente usado para representar números).

public interface Calculator<N extends Number> {
    N add(N a, N b);
    N subtract(N a, N b);
}
Enter fullscreen mode Exit fullscreen mode

S, U, V etc.: Múltiplos tipos (usado quando há mais de um parâmetro genérico).

public class Pair<S, T> {
    private S first;
    private T second;

    public Pair(S first, T second) {
        this.first = first;
        this.second = second;
    }

    public S getFirst() {
        return first;
    }

    public T getSecond() {
        return second;
    }
}
Enter fullscreen mode Exit fullscreen mode

Essas convenções ajudam a tornar o código mais legível e a compreender a finalidade dos parâmetros genéricos.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more