What's this generics usage in Java? X.method()

前端 未结 5 627
野性不改
野性不改 2021-02-07 06:22

I\'ve read the whole SCJP6 book Sierra and Bates book, scored 88% the exam.

But still, i never heard of how this kind of code works as it\'s not explained in the generic

5条回答
  •  没有蜡笔的小新
    2021-02-07 06:34

    Just a small addition to the other responses.

    When getting the according compiler error:

    While the "traditional" casting approach

    (Comparator) Collections.reverseOrder()
    

    looks similar to the generics approach

    Collections.reverseOrder()
    

    the casting approach is of course not type-safe (possible runtime exception), while the generics approach would create a compilation error, if there is an issue. Thus the generics approach is preferred, of course.

提交回复
热议问题