Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

Java Tutorial

Java HOMEJava IntroJava Get StartedJava SyntaxJava OutputJava CommentsJava VariablesJava Data TypesJava Type CastingJava OperatorsJava StringsJava MathJava BooleansJava If...ElseJava SwitchJava While LoopJava For LoopJava Break/ContinueJava Arrays

Java Methods

Java MethodsJava Method ParametersJava Method OverloadingJava ScopeJava Recursion

Java Classes

Java OOPJava Classes/ObjectsJava Class AttributesJava Class MethodsJava ConstructorsJava this KeywordJava ModifiersJava EncapsulationJava Packages / APIJava InheritanceJava PolymorphismJava super KeywordJava Inner ClassesJava AbstractionJava InterfaceJava AnonymousJava EnumJava User InputJava Date

Java Errors

Java ErrorsJava DebuggingJava ExceptionsJava Multiple ExceptionsJava try-with-resources

Java File Handling

Java FilesJava Create FilesJava Write FilesJava Read FilesJava Delete Files

Java I/O Streams

Java I/O StreamsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriter

Java Data Structures

Java Data StructuresJava CollectionsJava ListJava ArrayListJava LinkedListJava List SortingJava SetJava HashSetJava TreeSetJava LinkedHashSetJava MapJava HashMapJava TreeMapJava LinkedHashMapJava IteratorJava Algorithms

Java Advanced

Java Wrapper ClassesJava GenericsJava AnnotationsJava RegExJava ThreadsJava LambdaJava Advanced Sorting

Java Projects

Java Projects

Java How To's

Java How Tos

Java Reference

Java ReferenceJava KeywordsJava String MethodsJava Math MethodsJava Output MethodsJava Arrays MethodsJava ArrayList MethodsJava LinkedList MethodsJava HashMap MethodsJava Scanner MethodsJava File MethodsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriterJava Iterator MethodsJava Collections MethodsJava System MethodsJava Errors & Exceptions

Java Examples

Java ExamplesJava CompilerJava ExercisesJava QuizJava ServerJava SyllabusJava Study PlanJava Interview Q&AJava Certificate


JavaGenerics


Java Generics

Generics allow you to write classes, interfaces, and methods that work with different data types, without having to specify the exact type in advance.

This makes your code more flexible, reusable, and type-safe.


Why Use Generics?

  • Code Reusability: Write one class or method that works with different data types.
  • Type Safety: Catch type errors at compile time instead of runtime.
  • Cleaner Code: No need for casting when retrieving objects.

Generic Class Example

You can create a class that works with different data types using generics:

class Box<T> {
  T value; // T is a placeholder for any data type

  void set(T value) {
    this.value = value;
  }

  T get() {
    return value;
  }
}

public class Main {
  public static void main(String[] args) {
    // Create a Box to hold a String
    Box<String> stringBox = new Box<>();
    stringBox.set("Hello");
    System.out.println("Value: " + stringBox.get());

    // Create a Box to hold an Integer
    Box<Integer> intBox = new Box<>();
    intBox.set(50);
    System.out.println("Value: " + intBox.get());
  }
}

Try it Yourself »

T is a generic type parameter. It's like a placeholder for a data type.

  • When you create aBox<String>,T becomesString.
  • When you create aBox<Integer>,T becomesInteger.

This way, the same class can be reused with different data types without rewriting the code.


Generic Method Example

You can also create methods that work with any data type using generics:

public class Main {
  // Generic method: works with any type T
  public static <T> void printArray(T[] array) {
    for (T item : array) {
      System.out.println(item);
    }
  }

  public static void main(String[] args) {
    // Array of Strings
    String[] names = {"Jenny", "Liam"};

    // Array of Integers
    Integer[] numbers = {1, 2, 3};

    // Call the generic method with both arrays
    printArray(names);
    printArray(numbers);
  }
}

Try it Yourself »

Example Explained

  • <T> is a generic type parameter - it means the method can work with any type:String,Integer,Double, etc.
  • The methodprintArray() takes an array of typeT and prints every element.
  • When you call the method, Java figures out whatT should be based on the argument you pass in.

This is useful when you want to write one method that works with multiple types, instead of repeating code for each one.


Bounded Types

You can use theextends keyword to limit the types a generic class or method can accept.

For example, you can require that the type must be a subclass ofNumber:

class Stats<T extends Number> {
  T[] nums;

  // Constructor
  Stats(T[] nums) {
    this.nums = nums;
  }

  // Calculate average
  double average() {
    double sum = 0;
    for (T num : nums) {
      sum += num.doubleValue();
    }
    return sum / nums.length;
  }
}

public class Main {
  public static void main(String[] args) {
    // Use with Integer
    Integer[] intNums = {10, 20, 30, 40};
    Stats<Integer> intStats = new Stats<>(intNums);
    System.out.println("Integer average: " + intStats.average());

    // Use with Double
    Double[] doubleNums = {1.5, 2.5, 3.5};
    Stats<Double> doubleStats = new Stats<>(doubleNums);
    System.out.println("Double average: " + doubleStats.average());
  }
}

Try it Yourself »

Even thoughint values are used in the first case, the.doubleValue() method converts them todouble, so the result is shown with a decimal point.

Example Explained

  • <T extends Number>: RestrictsT to only work with numeric types likeInteger,Double, orFloat.
  • .doubleValue(): Converts any number to adouble for calculation.
  • Works for any array of numbers as long as the elements are subclasses ofNumber.

Generic Collections

Java Collections likeArrayList andHashMap use generics internally:

ArrayList<String> list = new ArrayList<>();
list.add("Apple");
String fruit = list.get(0); // No need to cast

Summary

  • Generics make your code flexible and type-safe.
  • UseT or another letter to define a type placeholder.
  • Generics can be applied to classes, methods, and interfaces.
  • Use bounds to limit what types are allowed.



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp