Class GenericsExamples

java.lang.Object
net.jrodolfo.java_evolution.java05.GenericsExamples

public class GenericsExamples extends Object
Demonstrates generics, introduced in Java 5.

Before generics, collections usually stored Object values. Callers had to cast values back to the expected type, so type mistakes could survive until runtime. Generics move that check into the type system.

  • Constructor Details

    • GenericsExamples

      public GenericsExamples()
  • Method Details

    • typedNames

      public List<String> typedNames(List<String> names)
      Creates a typed list of names.
      Parameters:
      names - names to copy
      Returns:
      a new list whose element type is known to the compiler
    • first

      public <T> T first(List<T> values)
      Returns the first element from a typed list without a cast.
      Type Parameters:
      T - the list element type
      Parameters:
      values - values to inspect
      Returns:
      the first value
    • firstRawValue

      public String firstRawValue(List rawValues)
      Shows the old raw-list shape that generics were designed to replace.
      Parameters:
      rawValues - raw values without an element type
      Returns:
      the first value cast to String
    • totalImportance

      public int totalImportance(Iterable<? extends GenericsExamples.ReleaseFeature> features)
      Reads feature importance from any iterable producer of GenericsExamples.ReleaseFeature values or subtypes.

      The ? extends ReleaseFeature wildcard says this method only reads feature values. That makes the API flexible: callers can pass Iterable<LanguageFeature> or Iterable<PlatformFeature> without copying those values into a less specific collection first.

      Parameters:
      features - features to inspect
      Returns:
      total importance score
    • describePrioritizedFeature

      public <T extends GenericsExamples.NamedFeature & GenericsExamples.PrioritizedFeature> String describePrioritizedFeature(T feature)
      Describes a value whose type parameter has multiple bounds.

      <T extends NamedFeature & PrioritizedFeature> is a multiple-bound type parameter. It lets the method require both capabilities without inventing a separate combined interface. This is one place where Java exposes an intersection-type-style constraint in normal source code.

      Type Parameters:
      T - type that satisfies both bounds
      Parameters:
      feature - feature that has both a name and a priority
      Returns:
      human-readable feature description