泛型和Java中的排序 [英] Generics and sorting in Java

查看:99
本文介绍了泛型和Java中的排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你在Java中编写一个静态函数来对数组进行排序,就像 Arrays.sort()一样。 Arrays.sort()的问题在于它接收一个Object数组,如果元素的元素抛出 ClassCastException 不要实现 Comparable



所以你希望你的函数接收一个子类型数组作为参数可比。类似的东西可以工作:

  static< T extends Comparable> void sort(T [] array); 

该签名的问题在于,您仍然可以传递一个可比较数组与整数和字符串,这会导致 RuntimeException



所以,你如何创建一个函数,元素实现Comparable并且具有所有相同的类型(例如Integer,String等)?

解决方案

使用

  static< T extends Comparable< ;? super T>> sort(T [] array); 

这是完成任务最常规的规范。基本上,它断言, T 是一种可以与自身进行比较的类型。


Suppose you write a static function in Java to sort an array, much like Arrays.sort(). The problem with Arrays.sort() is that it receives an array of Object, and throws a ClassCastException if its elements don't implement Comparable.

So you want your function to receive as an argument an array of a subtype of Comparable. Something like that could work:

static <T extends Comparable> void sort(T[] array);

The problem with that signature is that you can still pass an array of Comparables with Integers and Strings for instance, which would cause a RuntimeException.

So, how can you create a function that will receive only an array whose elements implement Comparable and have all the same type (e.g. Integer, String, etc?)

解决方案

Use

static <T extends Comparable<? super T>> sort(T[] array);

which is the most general specification to accomplish the task. Basically, it asserts, that T is a type which can be compared to itself.

这篇关于泛型和Java中的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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