Sobes.tech
Middle

What capabilities do Generics provide in Java?

sobes.tech AI

Answer from AI

Generics in Java enhance type safety of the code, preventing runtime errors related to type casting. Main features:

  • Type checking at compile time: The compiler verifies the correctness of the types used in Generics, allowing errors to be caught before program execution.

    // Without Generics - possible ClassCastException
    List list = new ArrayList();
    list.add("string");
    list.add(123); // Adding Integer
    String s = (String) list.get(1); // Runtime error
    
    // With Generics - compile-time error
    List<String> stringList = new ArrayList<>();
    stringList.add("string");
    // stringList.add(123); // Compile-time error
    String str = stringList.get(0); // Safe retrieval
    
  • Elimination of type casting: Generics eliminate the need for explicit type casting when retrieving elements from collections or using parameterized classes.

    // Without Generics
    List list = new ArrayList();
    list.add("Hello");
    String s = (String) list.get(0); // Explicit casting
    
    // With Generics
    List<String> stringList = new ArrayList<>();
    stringList.add("Hello");
    String str = stringList.get(0); // No casting needed
    
  • Implementation of generic code (Generics Methods, Generics Classes, Generics Interfaces): Allows creating generalized algorithms and data structures that work with different types without duplicating code.

    // Generic method for printing an array
    public static <T> void printArray(T[] array) {
        for (T element : array) {
            System.out.print(element + " ");
        }
        System.out.println();
    }
    
    // Generic class - pair of values
    class Pair<K, V> {
        private K key;
        private V value;
    
        public Pair(K key, V value) {
            this.key = key;
            this.value = value;
        }
    
        public K getKey() { return key; }
        public V getValue() { return value; }
    }
    
  • Support for Wildcards: Allows defining flexible constraints on types in parameterized types.

    • ? (Unbounded Wildcard): Any type.
    • ? extends T (Bounded Wildcard - Upper Bound): Type must be T or its subtype.
    • ? super T (Bounded Wildcard - Lower Bound): Type must be T or its supertype.
    // Method accepting a list of any type
    public static void processList(List<?> list) {
        // ...
    }
    
    // Method accepting a list of numbers or their subtypes
    public static void processNumbers(List<? extends Number> list) {
        // ...
    }
    
    // Method accepting a list of strings or their supertypes
    public static void addStrings(List<? super String> list) {
        list.add("new string");
    }
    
  • Usage in Collections Framework: All major collection classes (List, Set, Map, etc.) are parameterized, making working with collections type-safe and convenient.

Generics are a key element of modern Java, increasing the reliability and readability of the code.

What capabilities do Generics provide in Java? — QA /… - sobes.tech