制作一个通用比较器类 [英] Making a generic comparator class

查看:134
本文介绍了制作一个通用比较器类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图制作一个比较器,它可以接受任何类型的元素进行比较。我不确定如何创建课程。我只是想让它比较两个相同类型的元素(但是客户端提供的任何类型,例如:Integer,String,Double等),以查看哪个更大,然后是另一个。

  public class InsertionComparator实现比较器< T> 
{
/ **
*比较两个元素。
*
* @param f1您想比较的第一个元素。
* @param f2您想比较的第二个元素。
* @return -1,0,1一个是否大于,小于
*或相等。
* /
public int compare(< T> element1,< T> element2)
{
if(element1< element2)
{
返回-1;
}
else
{
if(element1> element2)
{
return 1;
}
else
{
return 0;



$ b

请帮助,谢谢!

解决方案

您可以对此做的最接近的事情是 Comparator 可以比较任何实现 Comparable 接口的对象:

  class NaturalComparator< T extends Comparable< T>>实现比较器< T> {
public int compare(T a,T b){
return a.compareTo(b);




$ b $ p
$ b

这是你可以做得最接近的:只有 Comparable 对象具有您要在此处建模的自然顺序。但通常情况下,一旦你有 Comparable 对象,你不一定需要 a 比较器 :例如, Collections.sort 可以带一个 List 和一个比较器 List 可比较元素。


I'm trying to make a comparator that can take any type of an element to compare. I'm unsure about how to create the class. I just want it to compare two elements of the same type (But whatever type the client gives it, ex: Integer, String, Double, etc...) to see which one is greater then the other.

public class InsertionComparator implements Comparator<T>
{
/**
 * Compares two elements.
 * 
 * @param  f1  The first element you want to compare.
 * @param  f2  The second element you want to compare.
 * @return  -1,0,1  Whether or not one is greater than, less than,
 * or equal to one another.
 */
public int compare(<T> element1,<T> element2)
{
    if(element1 < element2)
    {
        return -1;
    }
    else
    {
        if(element1 > element2)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    } 
}
}

Please help, thank you!

解决方案

The closest thing you can do to this is a Comparator that can compare any objects that implement the Comparable interface:

class NaturalComparator<T extends Comparable<T>> implements Comparator<T> {
  public int compare(T a, T b) {
    return a.compareTo(b);
  }
}

That's really the closest you can do: only Comparable objects have the "natural ordering" you're trying to model here. But generally, once you have Comparable objects, you don't necessarily need a Comparator: for example, Collections.sort can take either a List with a Comparator, or a List with Comparable elements.

这篇关于制作一个通用比较器类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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