简体   繁体   English

Java中泛型类的泛型容器

[英]generic container of a generic class in java

What should I write for "self" in Java? 我应该用Java为“自我”写什么? What I want "self" to mean here is "whatever class this concrete implementation of Vehicle is". 我想要“自我”在这里指的是“ Vehicle的具体实现是什么类”。 Is that possible in Java? 在Java中有可能吗?

import java.util.ArrayList;
import java.util.List;

abstract class Vehicle {
    private Garage<self> garage;

    void setGarage(Garage<self> g) {
        this.garage = g;
        g.vehicles.add(this);
    }
}

class Car extends Vehicle {
}

class Garage<T extends Vehicle> {
    List<T> vehicles = new ArrayList<>();

    void addVehicle(T t) {
        vehicles.add(t);
    }
}

public class GenericFoo {
    public static void main(String[] args) {
        Garage<Car> carGarage = new Garage<>();

        Car c = new Car();
        carGarage.addVehicle(c);
        c.setGarage(carGarage);
    }
}

It's possible to create something equivalent but requires some additional effort. 可以创建等效的东西,但需要额外的努力。 Hava a look at below code: 哈瓦看看下面的代码:

import java.util.ArrayList;
import java.util.List;

public class GenericsSample {

    public static void main(String[] args) {
        Garage<Car> carGarage = new Garage<>();

        Car c = new Car();
        carGarage.addVehicle(c);
        c.setGarage(carGarage);
    }

    abstract static class Vehicle<T extends Vehicle<T>> {

        private Garage<T> garage;

        void setGarage(Garage<T> g) {
            this.garage = g;
            g.vehicles.add(self());
        }

        abstract T self();
    }

    static class Car extends Vehicle<Car> {

        @Override
        Car self() {
            return this;
        }
    }

    static class Garage<T extends Vehicle<T>> {

        List<T> vehicles = new ArrayList<>();

        void addVehicle(T t) {
            vehicles.add(t);
        }
    }
}

What's important here: 这里重要的是:

  • Vehicle class parametrization - in fact, T type is Vehicle itself. Vehicle类参数化-实际上, T型是Vehicle本身。 We need it to be able to get actual type from parent level. 我们需要它能够从父级获取实际类型。 In our case, T represents Car (and can represent any subclass actually). 在我们的例子中, T代表Car (并且实际上可以代表任何子类)。 Vehicle<T extends Vehicle<T>> may look a bit tricky but, in fact, it's quite easy to understand - T is a "reference" to subclass from superclass. Vehicle<T extends Vehicle<T>>可能看起来有些棘手,但实际上,它很容易理解T是对超类的子类的“引用”。
  • self() method - I added self() method to Vehicle class. self()方法-我在Vehicle类中添加了self()方法。 Please notice that self() returns T , not Vehicle , what means that type of returned object is this concrete, implementation class. 请注意, self()返回T而不是Vehicle ,这意味着返回的对象类型是此具体的实现类。 Each implementation has to just return this . 每个实现都必须返回this

Hope it solves your problem. 希望它能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM