zoukankan      html  css  js  c++  java
  • TreeSet典型例子两个 比较器❤

    package com.runoob.Collection;
    
    import java.util.Comparator;
    import java.util.Set;
    import java.util.TreeSet;
    
    /*
     * 联系:对多个字符串(不重复)按照长度排序(由短到长)
     * 思路:
     * 1.多个字符串,需要容器存储
     * 2.选择哪个容器。字符串是对象,可以选择集合,而且不重复,选择set集合
     * 3.还需要排序,可以选择TreeSet集合
     */
    public class TreeSetTest {
    	public static void main(String[] args) {
    		
    		//sortStringbyLength();
    		sortStringbyLength2();
    
    	}
    
    	public static void sortStringbyLength(){
    
    		Set set = new TreeSet(new ComparatorByLength());
    
    		set.add("hahaha");
    		set.add("ab");
    		set.add("xxxx");
    		set.add("ttt");
    		set.add("lalalalala");
    
    		for(Object obj : set){
    			System.out.println(obj);
    		}
    	}
    
    
    	/*
    	 * 练习5:对多个字符串(重复),按照长度排序
    	 * 思路:
    	 * 1.能使用TreeSet吗?不能,
    	 * 2.可以存储到数组,list,这里先选择数组
    	 */
    
    	public static void sortStringbyLength2(){
    
    		String [] arr ={"hahaha","abccc","xixi","nba","cctv","zero","hahaha","xixi"};
    		
    		//自然排序可以使用String类中的compareTo方法
    		//但是现在要的是按照长度排序,这就需要比较器
    		
    		//定以一个按照长度排序的比较器对象
    		Comparator comp = new ComparatorByLength();
    		
    		for(int x=0;x<arr.length-1;x++){
    			for(int y =x+1;y<arr.length;y++){
    			//	if(arr[x].compareTo(arr[y])>0){//按照字典书序
    				if(comp.compare(arr[x], arr[y])>0)//按照长度顺序
    					swap(arr,x,y);
    				}
    			}
    		
    		
    		for(String s : arr){
    			System.out.println(s);
    		}
    		
    	}
    
    	private static void swap(String[] arr, int x, int y) {
    		// TODO Auto-generated method stub
    		String temp = arr[x];
    		arr[x] = arr[y];
    		arr[y] =temp;
    	}
    }
    

      ========================

    package com.runoob.Collection;
    
    import java.util.Comparator;
    
    public class ComparatorByLength implements Comparator {
    
    	@Override
    	public int compare(Object o1, Object o2) {
    		
    		//对字符串按照长度比较
    		String s1 =(String)o1;
    		String s2 =(String)o2;
    		
    		//比较长度
    		int temp =s1.length()-s2.length();
    		
    		//长度相同,再按照字典顺序
    		return temp==0?s1.compareTo(s2):temp;
    		
    	}
    
    }
    

      

  • 相关阅读:
    查找路径php.ini文件到底在哪里?
    对象androidandroid 开发中 如何取得ListView 的 每条Item 的对象
    文件内容红帽子数据库.profile文件内容详解
    思维流程对测试认识的三个阶段
    磁盘修改RHEL6使用udev修改asm磁盘名
    环境错误Unable to add window token android.app.LocalActivityManager$LocalActivityRecord@435def20 is not v
    deployconfigurationJboss remote access
    数据级别[Oracle] 事务隔离级别(Oracle的实现方式)
    Linux 基本命令
    PostThreadMessage
  • 原文地址:https://www.cnblogs.com/youning/p/7376625.html
Copyright © 2011-2022 走看看