做什么< 和> 意味着诸如实现 Comparable ?
在 Java 1.4.2 中,类 java.math.BigInteger
实现接口 Comparable
、Serializable
。
在 Java 1.5.0,类 java.math. BigInteger
实现接口Serialized
、Comparable
。
这只是一个帮助我询问 <
和 >
的示例。 我真正想知道的是 <
和 >
的东西。
我的问题有三个:
-
implements
语句的
部分是什么意思? - 这个语法叫什么?
- 它有什么作用?
PS:在谷歌上搜索 <
和 >
真的很难,也不可能搜索 <
和 >放在第一位。
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
阅读 Java 泛型教程。 尖括号之间的东西是一个类型参数 - Comparable 是一个泛型类,在这种情况下,尖括号意味着该类可以与其他 BigIntegers 进行比较。
对于这种情况的更多说明,请查看 Javadocs for Comparable 1.5 中。 请注意,它被声明为 意味着您必须有一个 ,这意味着它必须实现
Comparable
,并且compareTo
方法采用T
类型的参数。 T 是一个类型参数,在使用接口时“填充”。 因此,在这种情况下,声明您实现 ComparablecompareTo(BigInteger o)
方法。 另一个类可能实现ComparablecompareTo(String o)
方法。希望您能从上面的代码片段中看到好处。 在 1.4 中,
compareTo
的签名只能采用Object
,因为所有类型的类都实现了 Comparable,并且无法确切知道需要什么。 但是,使用泛型,您可以指定与特定类进行比较,然后编写一个更具体的compareTo 方法,该方法仅将该类作为参数。这里的好处有两个。 首先,您不需要在方法的实现中进行 的对象,因为类型不匹配。 编译器能够向您指出这一点要好得多,而不是像非通用代码中通常发生的那样导致运行时异常。
instanceof
检查和强制转换。 其次,编译器可以在编译时执行更多类型检查 - 您不会意外地将 String 传递给实现 ComparableRead the Java Generics Tutorial. The thing between the angle brackets is a type parameter - Comparable is a generic class, and in this case the angle brackets mean that the class is comparable to other BigIntegers.
For a little more clarification in this case, have a look at the Javadocs for Comparable in 1.5. Note that it is declared as
Comparable<T>
, and that thecompareTo
method takes an argument of typeT
. The T is a type parameter that is "filled in" when the interface is used. Thus in this case, declaring you implementComparable<BigInteger>
implies that you must have acompareTo(BigInteger o)
method. Another class might implementComparable<String>
meaning that it would have to implement acompareTo(String o)
method.Hopefully you can see the benefit from the above snippet. In 1.4, the signature of
compareTo
could only ever take anObject
since all kinds of classes implemented Comparable and there was no way to know exactly what was needed. With generics, however, you can specify that you are comparable with respect to a particular class, and then write a more specific compareTo method that only takes that class as a parameter.The benefits here are two-fold. Firstly, you don't need to do an
instanceof
check and a cast in your method's implementation. Secondly, the compiler can do a lot more type checking at compile time - you can't accidentally pass a String into something that implementsComparable<BigInteger>
, since the types don't match. It's much better for the compiler to be able to point this out to you, rather than have this cause a runtime exception as would have generally happened in non-generic code.我很确定它是泛型
http:// java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
我问了一些类似的东西(C#),那里有有用的信息Method 是什么? 意思是?
I'm pretty sure it is Generics
http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
I asked something similar (C#) it has useful info there What does Method<ClassName> mean?