package com.eduask;
import java.util.Comparator;
import java.util.Iterator;import java.util.TreeSet;/*
"90 -7 0 18 2 45 4"将字符串中的数值进行排序。使用TreeSet完成。
思路
1,将字符串切割。2,可以将这些对象存入TreeSet集合。因为TreeSet自身具备排序功能。*/public class TreeSetTest {
public static void main(String[] args) { int[] array = { 90, -7, 0, 18, 2, 45, 4 }; TreeSet set = new TreeSet(new MyComparator()); for (int i = 0; i < array.length; i++) { set.add(array[i]); } Iterator it = set.iterator(); while (it.hasNext()) { it.next(); } System.out.println(set); }}class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
if (o1 == null || o2 == null) {
throw new RuntimeException("不可以为空"); } if (!(o1 instanceof Object) || !(o1 instanceof Object)) { throw new RuntimeException("类型不对"); } int str1 = (int) o1; int str2 = (int) o2;int str = str1 < str2 ? -1 : (str1 == str2 ? 0 : 1);
return str; }}