zoukankan      html  css  js  c++  java
  • 48- java Arrays.sort和collections.sort()再次总结

    今天又碰到一个新BUG,记下来。

    一直报空指针异常,我就很奇怪了,怎么就空指针了呢,我输出时,也能输出东西呀。

    原来Arrays.sort() 和 Collections.sort() 都是对整个数组或者链表进行排序的,也就是整个数组或者链表有多长就会进行多长的排序。

    而我new的数组时30,而真正new的对象只有20个,故后10个对象没有实例化,而排序比较时有用到,故会报空指针异常。

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Scanner;
    
    public class Main 
    {
    	public static <T> void main(String[] args) { 
    		Scanner cin = new Scanner(System.in);
    		
    		// 对象链表排序
    		List<People> list =  new ArrayList<People>();
    		 
    		for(int i = 0; i < 20; i++) {
    			list.add(new People(20 - i, "ys" + i));
    		}
    
    		Collections.sort(list, new Comparator<People>() {
    			@Override
    			public int compare(People arg0, People arg1) {
    				// TODO Auto-generated method stub
    				return arg0.age - arg1.age;
    			}
    		});
    		
    		for(int i = 0; i < 20; i++) {
    			System.out.println(list.get(i).age + list.get(i).name);
    		}
    		
    		
    		// 对象数组排序
    		People[] peos = new People[20];
    		
    		for(int i = 0; i < 20; i++) {
    			peos[i] = new People(20 - i, "; song-" + i);
    		}
    		Arrays.sort(peos, new Comparator<People>() {
    
    			@Override
    			public int compare(People o1, People o2) {
    				// TODO Auto-generated method stub
    				System.out.println(o1.name);
    				return o1.age - o2.age;
    			}
    			
    		});
    		
    		System.out.println("===================");
    		for(int i = 0; i < 20; i++) {
    			System.out.println(peos[i].age + peos[i].name);
    		}
    	}
    }
    
    class People{
    	int age;
    	String name;
    	People(int age, String name){
    		this.age = age;
    		this.name = name;
    	}
    }
    

      

  • 相关阅读:
    动态规划 01背包问题
    日常水题 蓝桥杯基础练习VIP-字符串对比
    本博客导航
    2019 ICPC 南昌 (C E G L)
    [模板]线段树
    [模板]手写双端队列(或普通队列)
    2019 ICPC Asia Yinchuan Regional (G, H)
    与超级源点与超级汇点相关的两题POJ 1062, HDU 4725
    [模板]链式向前星
    [总结]关于反向建图
  • 原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/10545172.html
Copyright © 2011-2022 走看看