A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 294645832 中级黑马   /  2014-5-27 10:39  /  2894 人查看  /  7 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 294645832 于 2014-6-5 15:24 编辑

我想问一下如何对集合进行排序  如对ArrayList<Integer>中的元素进行数字大小的排序

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1 赞一个!

查看全部评分

7 个回复

倒序浏览
Collection.sort或者可以用转数组,然后就用冒泡或选择排序都行
回复 使用道具 举报
本帖最后由 杨韬略 于 2014-5-27 11:56 编辑

解答:集合中能对对象进行排序的只有TreeSet,所以你如果想对ArrayList里元素进行排序可以尝试将对象存进TreetSet在用TreeSet集合里的自定义排序方法进行对象排序。
以下是TreeSet集合排序具体步骤!

class  ComparetorInteger implements Comparator{

        public int compare(Object o1, Object o2) {
                Integer min = (Integer) o1;
                Integer max = (Integer) o2;
                int i = max-min;
                return (i == 0)?max-min:min-max;
        }
}

public class TreeSetDemo {

                public static void main(String[] args) {
         
                Test();
        }
        
        
        private static void Test(){
                TreeSet<Integer> treeSet = new TreeSet<Integer>(new ComparetorInteger());
                //从下面的运行结果来看,是根据首字母的排序进行输出的,
                treeSet.add(23);
                treeSet.add(1);
                treeSet.add(56);
                treeSet.add(78);
                treeSet.add(4);
               
                Iterator it = treeSet.iterator();
                while(it.hasNext()){
                        System.out.println(it.next());
                }
        }}

运行效果:
1
4
23
56
78

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1 很给力!

查看全部评分

回复 使用道具 举报
294645832 来自手机 中级黑马 2014-5-27 18:47:17
板凳
杨韬略 发表于 2014-5-27 11:54
解答:集合中能对对象进行排序的只有TreeSet,所以你如果想对ArrayList里元素进行排序可以尝试将对象存进Tre ...

请问一下  这一步是什么意思   return (i == 0)?max-min:min-max;
回复 使用道具 举报
294645832 来自手机 中级黑马 2014-5-27 18:48:19
报纸
294645832 发表于 2014-5-27 18:47
请问一下  这一步是什么意思   return (i == 0)?max-min:min-max;

看懂了  谢谢
回复 使用道具 举报

不用谢:lol
回复 使用道具 举报
杨韬略 发表于 2014-5-27 11:54
解答:集合中能对对象进行排序的只有TreeSet,所以你如果想对ArrayList里元素进行排序可以尝试将对象存进Tre ...

果然很吊
回复 使用道具 举报
DxxD 中级黑马 2015-3-27 10:27:24
8#
杨韬略 发表于 2014-5-27 11:54
解答:集合中能对对象进行排序的只有TreeSet,所以你如果想对ArrayList里元素进行排序可以尝试将对象存进Tre ...

个人觉得,你跟楼主说的不是一个问题,他说的是用ArrayList,你用的TreeSet,你说把ArrayList存进去TreeSet,但是从代码看的出,你是重新定义了TreeSet<Integer>,而不是把ArrayList存进去!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马