如何排序的对象基于一个属性一个ArrayList? [英] How to sort an arraylist of objects based on one property?

查看:90
本文介绍了如何排序的对象基于一个属性一个ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我知道有类似的问题在那里,所以你说之前的去google一下我已经尝试过,似乎我的情况是独一无二的。再次,我有学生对象的ArrayList。这些对象都具有共同的属性,如姓和名,UID(大学ID号)GPA,然后有针对研究生和本科生的子类。我一直难倒如何在最低阶的基础上的UID号ArrayList的排序,以最高的。 UID号是U123456的格式的字符串。总有一个U,然后整数的变化量。由于U型,我不能解析成一个int和排序的方式,我已经看到了正在使用的比较器类,但我不明白它,因为它似乎只比较两个对象?如果比较类将这项工作,可能有人请向我解释它做什么以及它是如何工作的?谢谢您的帮助!

Ok, I know there are similar questions out there, so before you say "go google it" I have already tried and it seems my situation is unique. Once again, I have an arrayList of Student objects. The objects all have common properties such as first and last name, UID (university ID number) GPA, and then there are subclasses for graduate and undergraduate. I have been stumped as to how to sort the arraylist based on the UID number in order of lowest to highest. The UID number is a STRING in the format of U123456. There is always a U, and then a varied amount of integers. Because of the U, I cannot parse into an int and sort that way, I have seen the Comparator class being used, but I do not understand it, as it seems to only compare two objects?! IF the comparator class will work for this, could someone please explain to me what it does and how it works? Thank you for your help!

推荐答案

这是很容易,因为这种行为进行比较:

It is easy to compare because of this behaviour:

System.out.println("u1".compareTo("u2")); // -1
System.out.println("u2".compareTo("u2")); // 0
System.out.println("u3".compareTo("u2")); // 1
System.out.println("u4".compareTo("u2")); // 2

所以这就是你需要做什么:

So this is what you need to do:

  • Let Student implement Comparable... you can look to http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
  • define compareTo(Student s) in Student, which is just return(this.id.compareTo(s.id));
  • just call sort() with the ArrayList

这篇关于如何排序的对象基于一个属性一个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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