简体   繁体   English

我使用泛型完成了什么?

[英]What am I accomplishing using generics?

I have the following code block:我有以下代码块:

public static void main(String[] args) {
    Integer[] test = new Integer[100];
    comparableTest(test);
    genericsTest(test);
}

private static void comparableTest(Comparable[] c) {

}

private static <E extends Comparable<E>> void genericsTest(E[] e) { }

What exactly am I accomplishing using the generics?我使用泛型到底要完成什么? These both have no compile errors.这些都没有编译错误。 I can still use the compareTo method.我仍然可以使用 compareTo 方法。 So what am I gaining using E extends Comparable<E> instead of just using Comparable ?那么我使用E extends Comparable<E>而不是仅仅使用Comparable什么?

The context for this question is that I am making sorting algorithms use the E extends Comparable<E> instead of Comparable .这个问题的上下文是我让排序算法使用E extends Comparable<E>而不是Comparable

Explanation解释

  • Without the generics you could get a class that is not comparable to itself but to other things.如果没有泛型,您可能会得到一个不能与自身相比,而是与其他事物相比的类。 Like an A implements Comparable<B> , this is unusual but possible.就像A implements Comparable<B> ,这是不寻常但可能的。

  • Also, you just lose type safety on the compareTo , as it then falls back to accepting Object s.此外,您只是在compareTo上失去了类型安全性,因为它然后回退到接受Object s。 So you could accidentally make a mistake, passing the wrong thing and Java can not help you and prevent it.所以你可能会不小心犯错,传递错误的东西,Java 无法帮助你和防止它。

For real, there is no reason why you should ever consider using raw types (dropping the generics) if you are not forced to develop for earlier than Java 5.实际上,如果您不是被迫为早于 Java 5 进行开发,则没有理由考虑使用原始类型(放弃泛型)。


Example例子

An example, considering your snippet, you pass Integer[] into it.例如,考虑您的代码段,您将Integer[]传递给它。 An Integer can not be compared to Dog s. Integer不能与Dog进行比较。 So if you accidentally do something stupid like:所以如果你不小心做了一些愚蠢的事情,比如:

Dog dog = new Dog();
if (c[0].compareTo(dog) == 0) { ... }

This will actually compile with the variant that takes Comparable[] , but crash on runtime when you execute it.这实际上将使用采用Comparable[]的变体进行编译,但在您执行它时会在运行时崩溃。 The other variant is able to detect this bug at compile-time and generally help you spot your mistake much earlier, which is good.另一个变体能够在编译时检测到此错误,并且通常可以帮助您更早地发现错误,这很好。

This example may look contrived but stuff like that can happen really quick.这个例子可能看起来很人为,但这样的事情可能会很快发生。


Note笔记

You might want to consider renaming your c to something that helps readability.您可能需要考虑将c重命名为有助于提高可读性的名称。 Someone reading a c might not know what it represents in your case, maybe it stands for a character, maybe a car.c可能不知道它在你的情况下代表什么,也许它代表一个字符,也许代表一辆车。

In general, try to avoid abbreviating.一般来说,尽量避免缩写。 What about comparables , elements or items . comparableselementsitems

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

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