• java list 排序


    Collections 有sort方法,但是如果list中保存的是一个自定义的对象,就需要自己来写排序的方法了,重写Comparator

    方法,实现自己的不同对象比较方法


    自定义对象:

    package com.java.datastructure;
    
    public class Peo
    {
    	private String name;
    	
    	private int age;
    	
    	@Override
    	public int hashCode()
    	{
    		final int prime = 31;
    		int result = 1;
    		result = prime * result + ((name == null) ? 0 : name.hashCode());
    		return result;
    	}
    
    	@Override
    	public boolean equals(Object obj)
    	{
    		if(this == obj) return true;
    		if(obj == null) return false;
    		if(getClass() != obj.getClass()) return false;
    		Peo other = (Peo) obj;
    		if(name == null)
    		{
    			if(other.name != null) return false;
    		}
    		else if(!name.equals(other.name)) return false;
    		return true;
    	}
    
    
    	public Peo()
    	{
    	}
    
    	public Peo(String name)
    	{
    		this.name = name;
    	}
    
    	public String getName()
    	{
    		return name;
    	}
    
    	public void setName(String name)
    	{
    		this.name = name;
    	}
    
    	public int getAge()
    	{
    		return age;
    	}
    
    	public void setAge(int age)
    	{
    		this.age = age;
    	}
    }
    

    测试方法:

    package com.java.datastructure;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    
    public class T2
    {
    	public static void main(String[] args)
    	{
    		t1();
    	}
    	
    	static void t1(){
    		boolean flag ;
    		List<Peo> list = new ArrayList<Peo>();
    		Peo peo = new Peo("j");
    		peo.setAge(100);
    		list.add(peo);
    	
    		Peo peo2 = new Peo("m");
    		peo2.setAge(79);
    		list.add(peo2);
    		Peo peo3 = new Peo("m");
    		peo3.setAge(200);
    		list.add(peo3);
    		for(Peo p:list){
    			System.out.println(p.getAge());
    		}
    		System.out.println("-------------------------------");
    		Collections.sort(list, new Comparator<Peo>()
    		{
    			@Override
    			public int compare(Peo o1, Peo o2)
    			{
    				return new Integer(o1.getAge()).compareTo(new Integer(o2.getAge()));
    			}
    		});
    		for(Peo p:list){
    			System.out.println(p.getAge());
    		}	
    		
    	}
    	
    }
    
    打印的结果为:

    100
    79
    200
    -------------------------------
    79
    100
    200



  • 相关阅读:
    video 属性和事件用法大全
    微信小程序 组件通信相关知识整理
    JavaScript实现登录窗口的拖拽
    JS 各种宽高
    CSS3 Animation
    CSS3 Transition
    CSS3 Transform
    vue 回到页面顶部
    element-ui 动态换肤
    Chrome浏览器下自动填充的输入框背景
  • 原文地址:https://www.cnblogs.com/wyang0126/p/5039903.html
Copyright © 2020-2023  润新知