有什么理由在Java中使用泛型吗? [英] Is there any reason to use generics in Java?

查看:53
本文介绍了有什么理由在Java中使用泛型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我错过了重点,但来自C#背景,我看不出有任何理由使用Java的泛型...

Perhaps I'm missing the point but coming from a C# background, I can't see any reason to use Java's generics...

在C#中,我有一个方法,它接受一个字符串并将其反序列化为一个对象...

In C# I've got a method which takes a string and deserializes it into an object...

public static Deserialize<T>(string source) {
    // Use reflection to examine T and determine
    // which properties I should be reading from
    // the string. Create an instance of T, 
    // populate the properties and return it
}

我可以这样称呼: x.Deserialize< AnyClass>("AnyClass的字符串表示形式");

类型擦除似乎使Java无法做到这一点?

Type erasure seems to make this impossible in Java?

我对泛型的下一个最常见用法是存储事物列表,但是由于我无法执行 List< int> ,并且必须装箱才能使用 List< Integer> ,当我可以只使用 int [] 时,似乎没有意义的装箱/拆箱.

My next most common usage of generics is storing things lists but since I can't do List<int> and have to box to use List<Integer>, it seems like pointless overhead boxing/unboxing when I could just use int[].

所以...是泛型做类似事情的唯一真正用途

So... Is the only real use for generics to do things like

List<MyClass> MyClassList = new List<MyClass>

并获得一些类型编译时类型检查?如果是这样的话,考虑到变量名称可以清楚地表明类型应该是什么(至少在我使用明智的命名约定的情况下),这似乎是多余的.

and get some type compile-time type checking? If so, it seems pretty redundant given that the variable name makes it clear what the type should be (at least as long as I'm using sensible naming conventions).

我忍不住觉得自己想念一些东西...

I can't help but feel I'm missing something...

推荐答案

好吧,如果您不使用泛型,那么每次都可以进行转换.您将必须:

Well, if you don't use generics, you get to cast each time. You would have to:

// if raw List
MyClass c = (MyClass) myClassList.get(0);
// if List<MyClass>
MyClass c = myClassList.get(0);

例如.

是的,泛型在运行时被删除,是的,它们仅在编译时用于强制类型安全.但是,当您使用界限时,仍然存在运行时类型擦除.示例:

Yes, generics are erased at runtime, yes, they are here to enforce type safety at compile time only; however there is still runtime type erasure when you use bounds. Example:

public <E extends RuntimeException> E get(final Class<E> c,
    final Throwable t)
{
    try {
        return (E) getHandle(c).invokeExact(t);
    } catch (Error | RuntimeException e) {
        throw e;
    } catch (Throwable oops) {
        final RuntimeException exception = new IllegalStateException(oops);
        exception.addSuppressed(t);
        throw exception;
    }
}

此处的 E 具有运行时类型擦除;它扩展了RuntimeException .因此,强制类型转换为 RuntimeException ,而不是 Object .

The E here has a runtime type erasure; it extends RuntimeException. Therefore the cast is to RuntimeException, not Object.

请参见 的javadoc> Collections.max() 以获得运行时类型擦除的另一个有趣示例(提示:为什么定义 T扩展Object& Comparable< ;? super T> 而不是 T扩展了Comparable< ;? super T> ?)

这篇关于有什么理由在Java中使用泛型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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