zoukankan      html  css  js  c++  java
  • TreeSet

    /*
    	Set : 无序,不可以重复元素
    		|--HashSet:数据结构是哈希表,线程是非同步的
    					保证元素唯一性原理: 判断元素的HashCode值是否相同
    					如果相同,还会继续判断元素的equals方法是否为True
    
    		|TreeSet: 可以对集合中的元素进行排序
    					底层数据结构是二叉树
    					保证元素唯一性的依据是
    					compareTo方法
    
    
    					TreeSet排序的第一种方式:让元素自身具备比较性
    					元素需要实现Comparable接口,覆盖compareTo方法
    					这种方式也称为元素的自然顺序,或者叫做默认顺序
    */
    
    import java.util.*;
    
    class Student implements Comparable//该接口强制让学生具备比较性
    {
    	private String name;
    	private int age;
    	Student(String name, int age)
    	{
    		this.name = name;
    		this.age = age;
    	}
    
    	public String getName()
    	{
    		return name;
    	}
    	public int getAge()
    	{
    		return age;
    	}
    
    	public int compareTo(Object obj)//覆盖父类中的函数
    	{
    		if( !(obj instanceof Student))
    			throw new RuntimeException("不是学生对象!");
    	
    		Student stu = (Student)obj;
    
    		if(this.age < stu.age)
    			return -1;
    		if(stu.age == this.age)
    			return this.name.compareTo(stu.name);//当主要条件相同时 ,也要判断次要条件
    
    		return 1;
    	}
    	
    }
    
    class TreeSetDemo
    {
    	public static void main(String []args)
    	{
    		TreeSet ts = new TreeSet();
    
    		ts.add(new Student("NUM3",33));
    		ts.add(new Student("NUM2",22));
    		ts.add(new Student("NUM1",11));
    		ts.add(new Student("NUM4",44));
    
    //		ts.add("aab");
    //		ts.add("aaa");
    //		ts.add("aaba");
    //		ts.add("cdb");
    //		ts.add("Dad");//大写的D 的ASCLL 码值比a 小
    //		//TreeSet 是按照元素的ASCLL 大小进行排序
    			
    
    		Iterator it = ts.iterator();
    
    		while( it.hasNext())
    		{
    			Student s = (Student)it.next();
    			sop( s.getName() + "  "+ s.getAge());
    		}
    	}
    	
    	public static void sop(Object obj)
    	{
    		System.out.println(obj);
    	}
    
    }

  • 相关阅读:
    php去除数组中重复值,并返回结果!
    SignalR 2 入门
    SignalR支持的平台
    SignalR简介
    作业调度系统quartz.net
    Oracle安装心得
    maven的项目目录解析
    web.xml的<url-parttern>的匹配规则
    Web.xml中四种验证方式
    Web.xml
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258524.html
Copyright © 2011-2022 走看看