ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume II
  5. Generic Types
Book 1 · Volume II — Generics, Collections & Type System · Topic 1.1

Generic Types

Generic classes, generic interfaces and generic methods

14 min readStage 1 · Foundations14 interview questions
Prerequisites
B1V1 Chapters 3–7
Covers
Generic classes · Generic interfaces · Generic methods
Related
1.2 Type Parameters · 2.1 Bounded Type Parameters · 3.2 Erasure Behavior
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

A generic type is a class or interface declared with one or more type parameters — placeholders for types that are supplied when the type is used. List<E> is generic; List<Order> is a parameterised type in which the type argument Order replaces E. A generic method declares its own type parameters, independent of any class.

The same code before and after generics
Figure 1 — The same code before and after generics

2Why It Exists

Before Java 5, collections held Object. Every read needed a cast, and nothing stopped the wrong type being inserted; errors surfaced as ClassCastException far from their cause. Generics let the compiler know what a container holds, so it can reject wrong insertions and insert the casts itself. One implementation of ArrayList then serves every element type safely.

3Core Concepts

Generic classes

A generic class declares its type parameters after its name: class Box<T>. Inside the class, T can be used as the type of fields, parameters and return values. At each use site the caller supplies a type argument, and the compiler checks every use against it.

Box<T> used with three different type arguments
Figure 2 — Box<T> used with three different type arguments

Generic interfaces

Interfaces are declared the same way: interface Repository<T, ID>, interface Comparable<T>. An implementing class either fixes the type argument (class OrderRepository implements Repository<Order, Long>) or stays generic itself (class InMemoryRepository<T, ID> implements Repository<T, ID>). Most of the JDK's generic types are interfaces: List, Map, Comparator, Function.

Generic methods

A generic method declares type parameters in angle brackets before its return type, and they are scoped to that method. It can be static or instance, in a generic or non-generic class. The compiler usually infers the type arguments from the method arguments and the target type (2.4); they can also be given explicitly, as in Collections.<String>emptyList().

The parts of a generic method declaration
Figure 3 — The parts of a generic method declaration

4How It Works Internally

Compile-time checking

When the compiler sees Box<String>, it checks every use against String: set(42) is rejected, and get() is known to return a String. All of this happens at compile time. The bytecode for that particular object carries no record that it was created as a Box<String>.

Erasure and inserted casts

The compiler then erases the type parameters. In Box<T>, T is replaced by its bound, which is Object when no bound is declared, so the class file contains one Box class with an Object field. At each call site the compiler inserts the cast that programmers used to write by hand: String s = box.get() compiles to a call that returns Object, followed by a checkcast to String. Because the compiler has already proven the cast is safe, it cannot fail unless raw types or unchecked warnings were ignored. Erasure is covered in detail in 3.2 and 3.3.

What javac does with Box<String>: check, erase, insert the cast
Figure 4 — What javac does with Box<String>: check, erase, insert the cast

Figure 4 shows both halves. javap -c on the caller shows the checkcast right after the call to get: the only trace of String in the compiled code.

One class for every type argument

Unlike C++ templates, Java does not generate a separate class for each type argument. Box<String>, Box<Order> and Box<Integer> share one Box class at run time, so generics add no code size. The price is that type arguments must be reference types: Box<int> is not allowed, and a Box<Integer> stores boxed Integer objects.

Bridge methods

When OrderRepository implements Repository<Order, Long>, its save(Order) method has a different erased signature from the interface's save(Object). The compiler therefore generates a hidden bridge method save(Object) that casts its argument and calls save(Order), so overriding keeps working after erasure. Bridge methods appear in reflection as synthetic methods and occasionally in stack traces.

A bridge method keeps overriding working after erasure
Figure 5 — A bridge method keeps overriding working after erasure

A caller holding a Repository calls the erased save(Object) (Figure 5); the bridge casts and delegates, so a wrong argument fails in the bridge. Example 3 shows both methods.

What survives in the class file

Erasure removes type arguments from objects, not from declarations. The class file keeps the generic signatures of classes, fields and methods in a Signature attribute, so reflection can report that a field is declared as List<Order>, and frameworks such as Spring and Jackson use this to inject beans or bind JSON by generic type. What running code cannot ask is which T a particular Box was created with; when a framework needs that, the type is passed explicitly, as a Class<T> or a type token.

5APIs / Features / Syntax

JAVADeclaring and using generic types
// Generic class
public final class Box<T> {
    private T value;
    public Box(T value) { this.value = value; }
    public T get() { return value; }
    public void set(T value) { this.value = value; }
}

// Generic interface, implemented with a fixed and with a generic argument
public interface Repository<T, ID> {
    Optional<T> findById(ID id);
    void save(T entity);
}
public class OrderRepository implements Repository<Order, Long> { … }
public class InMemoryRepository<T, ID> implements Repository<T, ID> { … }

// Generic methods
public static <T> List<T> repeat(T item, int times) {
    return Collections.nCopies(times, item);
}
public static <T extends Comparable<T>> T max(List<T> items) { … }

List<String> xs = repeat("a", 3);              // T inferred as String
List<Integer> ys = Utils.<Integer>repeat(7, 2); // explicit type argument

6Practical Examples

Example 1 — A generic result type for a service layer

Problem. Service methods that can fail with a business error need to return either a value or an error, for any value type, without throwing and without casts at the caller.

JAVAA generic interface, generic records and a generic method
// A generic result type used across a service layer
public sealed interface Result<T> permits Result.Ok, Result.Err {
    record Ok<T>(T value) implements Result<T> {}
    record Err<T>(String error) implements Result<T> {}

    // generic method
    default <R> Result<R> map(Function<? super T, ? extends R> f) {
        return switch (this) {
            case Ok<T> ok   -> new Ok<>(f.apply(ok.value()));
            case Err<T> err -> new Err<>(err.error());
        };
    }
}

Result<Order> r = orderService.place(request);
Result<Money> total = r.map(Order::total);

Why it works. Result<T> is a generic sealed interface whose two cases are generic records. map declares its own R, so a Result<Order> becomes a Result<Money> without a cast, and Order::total is checked against Order. Because the interface is sealed, the switch needs no default, and the diamond in new Ok<>(...) infers Ok<R> from the return type.

Example 2 — Mini program: one repository, two domain types

Problem. Section 9 calls generic types the building blocks of reusable infrastructure. This program builds the smallest useful piece of it: a generic Repository<T, ID>, an in-memory implementation and a generic Page<T> with a generic map method, then uses the one implementation for orders keyed by Long and customers keyed by String.

JAVATypedRepository.java
public class TypedRepository {
    interface Repository<T, ID> {
        void save(T entity);
        Optional<T> findById(ID id);
        Page<T> page(int number, int size);
    }
 
    record Page<T>(List<T> items, int number, int totalPages) {
        <R> Page<R> map(Function<? super T, ? extends R> f) {  // generic method
            List<R> mapped = items.stream().<R>map(f).toList();
            return new Page<>(mapped, number, totalPages);
        }
    }
 
    static final class InMemoryRepository<T, ID> implements Repository<T, ID> {
        private final Map<ID, T> rows = new LinkedHashMap<>();
        private final Function<T, ID> idOf;
        InMemoryRepository(Function<T, ID> idOf) { this.idOf = idOf; }
 
        public void save(T entity) { rows.put(idOf.apply(entity), entity); }
        public Optional<T> findById(ID id) {
            return Optional.ofNullable(rows.get(id));
        }
        public Page<T> page(int number, int size) {
            List<T> all = List.copyOf(rows.values());
            int from = Math.min(number * size, all.size());
            int to = Math.min(from + size, all.size());
            int pages = (all.size() + size - 1) / size;
            return new Page<>(all.subList(from, to), number, pages);
        }
    }
 
    record Order(Long id, String customer, int cents) {}
    record Customer(String email, String name) {}
 
    public static void main(String[] args) {
        Repository<Order, Long> orders = new InMemoryRepository<>(Order::id);
        Repository<Customer, String> customers =
                new InMemoryRepository<>(Customer::email);
        for (long id = 1; id <= 5; id++)
            orders.save(new Order(id, "c" + id, (int) id * 1_000));
        customers.save(new Customer("asha@example.com", "Asha"));
 
        Order o = orders.findById(3L).orElseThrow();              // no cast
        String name = customers.findById("asha@example.com")
                               .map(Customer::name).orElse("?");
        System.out.println("found:    " + o);
        System.out.println("customer: " + name);
        Page<Order> p = orders.page(1, 2);
        System.out.println("page " + p.number() + " of " + p.totalPages()
                + ": " + p.items().size() + " orders");
        Page<String> labels = p.map(x -> "#" + x.id() + " " + x.cents() / 100);
        System.out.println("labels:   " + labels.items());
        // orders.save(new Customer("x", "y")); // error: not an Order
    }
}
OUTPUT
found:    Order[id=3, customer=c3, cents=3000]
customer: Asha
page 1 of 3: 2 orders
labels:   [#3 30, #4 40]

Why it behaves this way. The class is written once; each declaration such as Repository<Order, Long> fixes T and ID, so findById(3L) gives an Order without a cast and the customer repository accepts only String keys. The key extractors Order::id and Customer::email are checked against the element type, and Page.map declares its own R. The commented-out line is the point: a Customer in the order repository is a compile error, not a production ClassCastException.

Example 3 — Seeing erasure and the bridge method with reflection

Problem. Section 4 says that every parameterisation shares one class, that declarations keep their generic signatures, and that the compiler adds bridge methods. This program checks all three claims at run time.

JAVABridgeSpy.java
public class BridgeSpy {
    interface Repository<T> { void save(T entity); }
    record Order(long id) {}
    static class OrderRepository implements Repository<Order> {
        public void save(Order order) { System.out.println("saved " + order); }
    }
    static class Box<T> { T value; List<Order> history = new ArrayList<>(); }
 
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void main(String[] args) throws Exception {
        // 1. one class for every type argument
        Box<String> s = new Box<>();
        Box<Integer> i = new Box<>();
        System.out.println(s.getClass() == i.getClass());
        // 2. erased field types, and the declarations kept in the class file
        Field value = Box.class.getDeclaredField("value");
        Field history = Box.class.getDeclaredField("history");
        for (Field f : List.of(value, history))
            System.out.println(f.getType().getSimpleName() + " / "
                    + f.getGenericType());
        // 3. the methods javac generated for OrderRepository
        Arrays.stream(OrderRepository.class.getDeclaredMethods())
              .sorted(Comparator.comparing(Method::isBridge))
              .forEach(m -> System.out.println(m.getName() + "("
                      + m.getParameterTypes()[0].getSimpleName() + ")"
                      + (m.isBridge() ? "  bridge, synthetic=" + m.isSynthetic()
                                      : "")));
        // 4. a call through the erased interface goes through the bridge
        Repository raw = new OrderRepository();
        raw.save(new Order(1));
        try {
            raw.save("not an order");
        } catch (ClassCastException e) {
            System.out.println("bridge cast: " + e.getClass().getSimpleName());
        }
    }
}
OUTPUT
true
Object / T
List / java.util.List<BridgeSpy$Order>
save(Order)
save(Object)  bridge, synthetic=true
saved Order[id=1]
bridge cast: ClassCastException

Why it behaves this way. Box<String> and Box<Integer> share one Class. The field declared as T has the erased type Object, but getGenericType() reads T and List<BridgeSpy$Order> from the Signature attribute. OrderRepository declares one method and reflection finds two, the second being the synthetic bridge; the raw calls pass through it, so the String fails at its cast.

Example 4 — A type token for List<Order>

Problem. Section 8 explains that JSON libraries need the full type, List<Order>, and that List.class is not enough. Jackson's TypeReference and Spring's ParameterizedTypeReference solve this with a type token. This program builds a minimal one to show how it works.

JAVATypeTokens.java
public class TypeTokens {
    // Captures T from an anonymous subclass: new TypeRef<List<Order>>() {}
    abstract static class TypeRef<T> {
        final Type type;
        protected TypeRef() {
            // generic superclass of the anonymous class: TypeRef<List<Order>>
            Type parent = getClass().getGenericSuperclass();
            type = ((ParameterizedType) parent).getActualTypeArguments()[0];
        }
    }
    record Order(long id) {}
 
    public static void main(String[] args) {
        Class<?> token = List.class;                // all a Class can say
        System.out.println("Class token:   " + token.getName());
        TypeRef<List<Order>> ref = new TypeRef<>() {};
        System.out.println("type token:    " + ref.type.getTypeName());
        ParameterizedType pt = (ParameterizedType) ref.type;
        System.out.println("raw type:      " + pt.getRawType().getTypeName());
        Type arg = pt.getActualTypeArguments()[0];
        System.out.println("type argument: " + arg.getTypeName());
        List<Order> orders = new ArrayList<>();
        System.out.println("an instance:   " + orders.getClass().getName());
    }
}
OUTPUT
Class token:   java.util.List
type token:    java.util.List<TypeTokens$Order>
raw type:      java.util.List
type argument: TypeTokens$Order
an instance:   java.util.ArrayList

Why it behaves this way. There is only one List class, so List.class cannot carry Order. The trailing {} declares an anonymous subclass of TypeRef<List<Order>>, and declarations survive erasure: getGenericSuperclass() reads the type back as a ParameterizedType. The object in the last line knows only its class, ArrayList, which is why Jackson asks for new TypeReference<List<Order>>() {}.

7Common Problems & Mistakes

MistakeConsequenceBetter approach
Using raw types (List list)All type checks are switched off for that variable; unchecked warnings appear, and a wrong element fails later as a ClassCastException (3.2)Always supply type arguments, or List<?> when the element type does not matter
Redeclaring the class's type parameter on a method (class Box<T> { <T> void m(T t) })The method's T shadows the class's T; the two are unrelated, and assignments between them do not compileUse the class's T without redeclaring it, or give a different parameter another name such as U
Generic parameters that could simply be interfaces (<T extends Shape> void draw(T s))The signature is harder to read and gives nothing over void draw(Shape s), because T is used only onceMake a method generic only when T links two positions, e.g. a parameter and the return type
Trying to create new T() or new T[]Does not compile: after erasure there is no T at run time to instantiate (3.3)Ask the caller for a Supplier<T>, a Class<T> or an IntFunction<T[]>
Passing List.class to a JSON or HTTP client for a List<Order>The library cannot see Order and builds a list of maps; the first use as an Order throws ClassCastExceptionPass a type token: TypeReference, ParameterizedTypeReference (Example 4)
Deeply nested generic types in a public API (Map<String, List<Map<Long, Order>>>)Callers cannot read or change the contract; every refactoring touches many signaturesIntroduce a named type for the structure and expose that

8Performance & Production Considerations

Generics have no run-time cost of their own: after erasure the bytecode is the same as hand-written code with casts, and the JIT compiler removes most of those checks. The real performance concern is boxing. A List<Integer> stores each number as a separate Integer object of about 16 bytes plus a reference, compared with 4 bytes per element in an int[]. For large numeric data, use primitive arrays, IntStream or a primitive collections library.

The most common generics failure in production is heap pollution: a raw type or an ignored unchecked warning lets the wrong type into a collection, and the ClassCastException appears later, far from where the bad element was added, often in a different request or thread. Treat unchecked warnings as errors in the build (-Xlint:unchecked with -Werror), and suppress them only on the smallest possible scope, with a comment explaining why the code is safe.

Libraries that deserialise generic types need the full type at run time. Reading JSON into List<Order> with Jackson requires a TypeReference<List<Order>>, and Spring's RestClient uses ParameterizedTypeReference for the same reason. Passing List.class silently produces a list of maps, which fails with a ClassCastException as soon as an element is used as an Order.

9Architecture & Design Considerations

Generic types are the building blocks of reusable infrastructure: repositories, result and response wrappers, event envelopes (Event<T>), caches (Cache<K, V>), pagination (Page<T>). They let one well-tested implementation serve many domain types. Keep them small and focused, and prefer a clear domain type over deeply nested generics in public APIs: Map<String, List<Map<Long, Order>>> is a sign that a named class is missing.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is a generic class?

A generic class declares one or more type parameters after its name, such as class Box<T>, and uses them as the types of its fields, parameters and return values. Code that uses the class supplies a type argument, as in Box<String>, and the compiler then checks every use against it: box.set(42) is rejected, and box.get() returns a String without a cast. One implementation therefore serves many element types safely. ArrayList<E> and HashMap<K, V> are the best-known examples. Because of erasure, all parameterisations share one class at run time, so the type argument exists only for the compiler.

Q2L2 · IntermediateCode

How do you declare a generic method, and how are its type arguments determined?

Declare the type parameters in angle brackets before the return type, for example public static <T> T first(List<T> items). They are scoped to that method and are independent of any class type parameters, so generic methods can live in non-generic utility classes. At the call site the compiler usually infers the type arguments from the method arguments and from the target type of the expression: in String s = first(names), T is inferred as String. When there is no target type to infer from, for example at the start of a chained call such as emptyList().stream().map(String::length), where T would be inferred as Object, you can supply the argument explicitly: Collections.<String>emptyList().

Q3L2 · IntermediateConcept

What is the difference between a generic type and a parameterised type?

A generic type is the declaration that has type parameters, such as List<E> or Map<K, V>; it describes a family of types. A parameterised type is one member of that family, a use of the generic type with actual type arguments supplied, such as List<String> or Map<Long, Order>. The distinction matters when reading compiler messages and the Java Language Specification. It also matters at run time: because of erasure, every parameterised type of List shares the same class, so List<String>.class does not exist and instanceof List<String> is not allowed.

Q4L3 · Senior EngineerCode

How can a class implement a generic interface?

There are two ways. The class can fix the type arguments, as in class OrderRepository implements Repository<Order, Long>; its methods then work with Order and Long directly, which suits a concrete domain implementation. Or the class can stay generic and pass its own parameters through, as in class InMemoryRepository<T, ID> implements Repository<T, ID>, which suits reusable infrastructure. A class can also mix the two, fixing one argument and keeping the other generic. In the fixed case, the compiler generates bridge methods so that the erased interface methods still dispatch to the typed implementations.

Q5L3 · Senior EngineerTrade-off

When is a generic method better than a method taking an interface type?

Use a generic method when the type parameter links two or more positions in the signature. In <T> T firstOrDefault(List<T> items, T fallback), the return type must match the element type and the fallback; an interface parameter could not express that, and callers would need casts. Likewise <T extends Comparable<T>> T max(List<T> items) returns exactly the caller's type. If the type parameter appears only once, as in <T extends Shape> void draw(T s), it adds nothing over void draw(Shape s), and the plain interface version is simpler to read and maintain.

Q6L4 · Technical ArchitectTrade-off

How do generics contribute to reusable enterprise infrastructure, and where do they hurt?

Generics let one well-tested implementation of infrastructure serve every domain type with compile-time safety: repositories, result and response wrappers, event envelopes such as Event<T>, caches such as Cache<K, V> and pagination such as Page<T>. Spring Data's JpaRepository<T, ID> is a familiar example. They hurt when public APIs expose deeply nested or wildcard-heavy types, such as Map<String, List<Map<Long, Order>>>, which are hard to read, document and change. Wrapping such structures in named domain types keeps APIs clear. Remember too that erasure hides type arguments at run time, so frameworks sometimes need explicit type tokens.

Q7L1 · BasicConcept

Why can you not write Box<int>, and what do you use instead?

Type arguments must be reference types, because after erasure a type parameter becomes Object (or its bound) and an int is not an object. Use the wrapper type, Box<Integer>, and autoboxing converts between int and Integer at the call site. For large amounts of numeric data that boxing costs memory and time, so use int[], IntStream or a primitive collection library there (section 8).

Q8L2 · IntermediateCode

What does this program print?

JAVABoxCounter.java
public class BoxCounter {
    static class Box<T> {
        static int created;              // one field for every Box<...>
        final T value;
        Box(T value) { this.value = value; created++; }
    }
 
    public static void main(String[] args) {
        Box<String> a = new Box<>("x");
        Box<Integer> b = new Box<>(42);
        System.out.println(Box.created);
        System.out.println(a.getClass() == b.getClass());
        System.out.println(a.getClass().getSimpleName() + " "
                + b.value.getClass().getSimpleName());
    }
}

It prints 2, then true, then Box Integer. There is one class Box for every type argument, so Box<String> and Box<Integer> share the static field created, which both constructors increment, and getClass() returns the same Class object for both. The simple name has no type argument because the object does not know it; the value inside does know its own class, Integer. This is also why a static field cannot use the class's T (1.2).

Q9L3 · Senior EngineerInternals

What is a bridge method, and when does the compiler generate one?

A bridge method is a synthetic method that javac adds when a class overrides or implements a generic method with a more specific signature, so that the erased signature still dispatches correctly. In class OrderRepository implements Repository<Order>, the interface method erases to save(Object) but the class declares save(Order); javac adds save(Object), which casts and calls save(Order) (Figure 5). Bridges also appear for covariant return types. Reflection reports them with isBridge() and isSynthetic(), and they sometimes appear as an extra frame in stack traces.

Q10L3 · Senior EngineerTricky

Why does Box<Object> b = new Box<String>("x") not compile, when String is a subtype of Object?

Because parameterised types are invariant: Box<String> is not a subtype of Box<Object>, even though String is a subtype of Object. If the assignment were allowed, b.set(42) would be legal through the Box<Object> reference and would put an Integer into a box that other code reads as a Box<String>. Arrays are covariant and pay for it with a run-time ArrayStoreException; generics reject the code at compile time instead. When a method should accept a box of any type, it declares a wildcard parameter such as Box<?> or Box<? extends Number> (Chapter 2).

Q11L3 · Senior EngineerScenario

After a refactoring, a service fails in production with "class java.util.LinkedHashMap cannot be cast to class Order" when it reads a cached list of orders. What happened, and how do you fix it?

The JSON library was given List.class, so it could not see Order and built a LinkedHashMap for each object. The result reached a List<Order> through an unchecked conversion, and the failure appears at the cast javac inserted where an element is first used as an Order. Pass a type token, new TypeReference<List<Order>>() {} for Jackson or ParameterizedTypeReference for Spring's RestClient (Example 4), or read an Order[], whose element type survives at run time, and add a test that reads the cached value back and uses an element.

Q12L4 · Technical ArchitectDesign

Design a generic event envelope for a messaging platform used by many teams.

An immutable record such as record Event<T>(String id, String type, Instant occurredAt, Map<String, String> headers, T payload) gives every team the same tracing and idempotency fields with a typed payload. Because T is erased, the type field and a registry from type names to payload classes tell the consumer what to deserialise. Keep one type parameter, version the payload records, and let a dispatcher call typed EventHandler<T> implementations, so the lookup and the cast live in one tested place.

Q13L5 · Solution ArchitectTrade-off

Your platform team proposes one generic base repository, Repository<T, ID>, for every service. Others want each service to write its own domain-specific repositories. How do you decide?

A shared generic base removes duplicated CRUD code and gives consistent paging, auditing and error handling, fixed once for everyone. The costs are coupling to the platform's releases, a base that grows methods only some services need, and generic findAll-style methods that ignore each domain's access patterns. A thin generic base for the mechanics, hidden behind domain interfaces such as OrderRepository that expose only the needed queries, usually balances the two. Decide on evidence: how much code is really duplicated, how often services diverge, and who owns the shared module.

Q14L5 · Solution ArchitectScenario

A twelve-year-old shared library used by thirty services exposes raw types (List, Map) in its public API. How would you migrate it to generics without a big-bang release?

Erasure was designed for this: changing List to List<Order> in a signature leaves the erased descriptor unchanged, so compiled callers keep working. Add type arguments to the library and fix its own warnings first, and release it as a minor version; raw callers only get unchecked warnings. Then track -Xlint:unchecked warnings per service as the migration metric, fix module boundaries first, and make -Werror the standard when the count nears zero. Avoid adding bounds: <T extends Comparable<? super T>> changes the erasure to Comparable and breaks compiled callers, which is why Collections.max declares T extends Object & Comparable<? super T> (2.1).

Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Generic classes and interfaces declare type parameters; users supply type arguments.
  • Generic methods declare their own parameters before the return type; arguments are usually inferred.
  • Generics move type errors from run time to compile time and remove casts.
  • Use generics where a type links several parts of a signature; prefer named types over deep nesting.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.