Java Comparator给出了要比较的属性的名称 [英] Java Comparator given the name of the property to compare

查看:80
本文介绍了Java Comparator给出了要比较的属性的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是这个;我必须订购一个数据表。表的每一行都是一个存储在List中的对象(我们称之为TableObject)。每一列数据都是类的属性(通常是String)。

My problem is this; I have to order a table of data. Each row of the table is an object (lets call it TableObject) stored in a List. Each column of data is a property of the class (usually a String).

当用户点击任何列时,我必须执行典型的数据排序。所以我想到将列表更改为TreeSet并在我的TableObject中实现Comparator。

I have to do the typical ordering of data when the user clicks on any column. So I thought about changing the List to a TreeSet and implementing Comparator in my TableObject.

问题出现在我尝试重新排序TreeSet时。首先比较是很容易的(parseInt中的异常的cheeking已被省略):

The problem comes when I try to reorder the TreeSet. The compare is fairly easy at first (cheeking for exceptions in parseInt have been omitted):

   public int compare(TableObject to1, TableObject to2){
        TableObject t1 = to1;
        TableObject t2 = to2;

        int result = 1;

        if(Integer.parseInt(t1.getId()) == Integer.parseInt(t2.getId())){result=0;}
        if(Integer.parseInt(t1.getId()) < Integer.parseInt(t2.getId())){result=-1;}

        return result;

    }

但是当我必须重新排序数据文本或者通过其他几十个数据,TableObject有我有一个问题。
我不想创建几十个比较函数,每个为一个。我不喜欢使用开关(或一连串的ifs)来决定如何比较对象。

But when I have to reorder by the text of the data or by other dozens of data that the TableObject has I have a problem. I do not want to create dozens of compare functions, each for one. I prefer not to use a switch (or a chain of ifs) to decide how to compare the object.

有什么办法以某种方式做这个),这不意味着我会写几百行几乎相同的代码?

Is there any way to do this in some way (like Reflexive), that doesn't imply that I will write like hundreds of lines of nearly the same code?

感谢所有!

推荐答案

Bean比较器应该工作。

这篇关于Java Comparator给出了要比较的属性的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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