java generics

java generics

In Java, generics allow you to define classes, interfaces, and methods that can work with different types of objects. Generics provide a way to specify the type of an object when you create a class, interface, or method, and to use that type in a type-safe way.

Here's an example of a generic class in Java:

public class Box<T> {
  private T t;

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

  public T get() {
    return t;
  }
}
Source:w‮l.ww‬autturi.com

This class defines a Box that can hold an object of any type. The type of the object is specified using a type parameter, T. The set() and get() methods of the Box class use the type parameter T to specify the type of the object that is being set or retrieved.

To use the Box class, you can specify the type of the object that the Box will hold when you create an instance of the class. For example:

Box<String> stringBox = new Box<>();
stringBox.set("Hello, world!");
System.out.println(stringBox.get()); // prints "Hello, world!"

Box<Integer> intBox = new Box<>();
intBox.set(123);
System.out.println(intBox.get()); // prints "123"

In this example, the stringBox variable is assigned an instance of the Box class that can hold a String object, and the intBox variable is assigned an instance of the Box class that can hold an Integer object. The type of the object that the Box will hold is specified using the type parameter when the Box is created.

Generics are used extensively in the Java Standard Library, and they can be useful when you want to create reusable and type-safe code.

Created Time:2017-11-03 22:21:07  Author:lautturi