Wednesday, January 22, 2025
HomeProgrammingWhat are Generics in Java?

What are Generics in Java?

Generics in Java are a powerful feature that allows you to define classes, interfaces, and methods with type parameters. Generics provide type safety and reusability by allowing you to work with different data types while avoiding type casting and runtime errors.

Key Concepts of Generics

  1. Type Parameter:
    • A placeholder for a type, specified within angle brackets (<>).
    • Example:
      public class Box<T> {
          private T item;
      
          public void set(T item) {
              this.item = item;
          }
      
          public T get() {
              return item;
          }
      }
      
  2. Type Safety:
    • Generics ensure that only the specified type can be used, reducing runtime errors.
    • Without generics, you would need to cast objects explicitly, increasing the chance of ClassCastException.
  3. Reusability:
    • Generic classes or methods can be reused for different data types without writing additional code.
See also  CSS Border

Advantages of Generics

  1. Compile-Time Type Checking:
    • Errors are caught during compilation rather than at runtime.
    • Example:
      List<String> list = new ArrayList<>();
      list.add("Hello");
      // list.add(123); // This will result in a compile-time error
      
  2. Elimination of Explicit Type Casting:
    • Without generics:
      List list = new ArrayList();
      list.add("Hello");
      String s = (String) list.get(0); // Manual casting
      
    • With generics:
      List<String> list = new ArrayList<>();
      list.add("Hello");
      String s = list.get(0); // No casting needed
      
  3. Code Reusability:
    • Generic methods and classes work with any type, reducing the need to write duplicate code for different types.
See also  Does C Have A String Type? [closed]

Examples of Generics

1. Generic Class

public class Box<T> {
    private T item;

    public void set(T item) {
        this.item = item;
    }

    public T get() {
        return item;
    }

    public static void main(String[] args) {
        Box<String> stringBox = new Box<>();
        stringBox.set("Hello");
        System.out.println("String value: " + stringBox.get());

        Box<Integer> intBox = new Box<>();
        intBox.set(123);
        System.out.println("Integer value: " + intBox.get());
    }
}

Output:

String value: Hello
Integer value: 123

2. Generic Method

You can define a generic method within a class or interface.

public class GenericMethodExample {
    public static <T> void printArray(T[] array) {
        for (T element : array) {
            System.out.println(element);
        }
    }

    public static void main(String[] args) {
        Integer[] intArray = {1, 2, 3};
        String[] stringArray = {"A", "B", "C"};

        System.out.println("Integer Array:");
        printArray(intArray);

        System.out.println("String Array:");
        printArray(stringArray);
    }
}

Output:

Integer Array:
1
2
3
String Array:
A
B
C

3. Generic Interface

public interface Pair<K, V> {
    K getKey();
    V getValue();
}

class KeyValue<K, V> implements Pair<K, V> {
    private K key;
    private V value;

    public KeyValue(K key, V value) {
        this.key = key;
        this.value = value;
    }

    @Override
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x