通用构造函数的好处 [英] Benefit of Generic Constructors

查看:112
本文介绍了通用构造函数的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有非泛型类的泛型构造函数有什么好处? Java规范允许:

What is the benefit of having generic constructor for a non-generic class? Java spec permits the following:

class NonGeneric {
  <T> NonGeneric() { }
  ...
  NonGeneric ref = new <String> NonGeneric();
}

我们可以拿出一个现实的例子,说明何时增强类?如何比首先使用Generic更好。

Can one come up with a realistic example of when it enhances the typesafety of the class? How would it be better than using Generic in the first place.

据我所知,Java设计者希望构造函数更加符合方法。
鉴于构造函数可能有副作用,泛型构造函数可以使用泛型来改变一些参数不被保留的参数,如

I understand that Java designers wanted the constructors to be more consistent with methods. Given that constructors can have side-effects, generic constructors can use generics to mutate some parameters whose references aren't retained, as in

<T> NonGeneric(T obj, List<T> list) {
  list.add(obj);
  // Don't hold a reference to list
}


推荐答案

我能想到的唯一用法是如果构造函数在运行时需要使用通用对象,但一旦完成后就不会存储该对象。

The only use that I can think of would be if the constructor needed to use a generic object while it was running, but did not store that object once it was complete.

例如:

For example:

<T> NonGeneric(T[] blank, List<T> list) {
    // Sort that list
    T[] array = list.toArray(blank);
    Arrays.sort(array);

    // Pull out the values as strings
    this.list = new ArrayList<String>(array.length);
    for (T value : array) {
        this.list.add(value.toString());
    }
}

这很可能只是语言设计者决定的东西以防万一有人想要它,因为没有理由阻止人们这样做。

It is most likely just something that the language designers decided to do just in case somebody wanted it, since there was no reason to prevent people from doing it.

这篇关于通用构造函数的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆