package caf;
import java.util.Arrays;
import java.util.TreeSet;
class Drink implements Comparable
{
public String name;
public Drink(String name)
{
this.name = name;
}
// 根据字符串的字符自然顺序做比较
// 该方法中的this指的是新加入集合的元素
// 而参数o指的是需要对比的元素
// 按照正常的逻辑思维应该是返回为负数是往后放
// 返回为正数放前边
public int compareTo1(Object o)
{
char[] a = name.toCharArray(), b = ((Drink) o).name.toCharArray();
System.out.println(name+"..."+((Drink) o).name);
int index = 0;
//如果表达式不成立,即相同索引位置的字符不想等
//那么跳出循环并根据该位置的字符顺序返回
//For example abc aba
//这种情况下在第2索引跳出,并返回c-a,也就是-2
while (a[index] == b[index])
{
//如果a到达字符串末尾,并且b仍有字符,那么返回-1
//表示this应该往后放
if (index == a.length - 1 && index < b.length - 1)
{
return -1;
}
//如果b到达字符串末尾,并且a仍有字符,那么返回1
//表示this应该往前放
else if (index == b.length - 1 && index < a.length - 1)
{
return 1;
}
//如果两个字符串都没有到达末尾,并且之前的字符都相等
//比较下个字符
index++;
//如果两个字符串都到达末尾,那么表示两个字符串相等
if(index == a.length && index == b.length)
{
return 0;
}
}
return a[index] - b[index];
}
//将两个字符串做成相等长度,长度少的末尾补0
//逐字符对比,如果索引位置不相等,就返回该
//索引位置字符的差
public int compareTo(Object o)
{
String thisStr = name;
String otherStr = ((Drink) o).name;
//计算2个字符串的最大长度
//初始化字符索引从0开始
int max = Math.max(thisStr.length(), otherStr.length());
int index = 0;
//对a b两个字符数组进行长度少的补0操作
//使其长度相等
char[] a = new char[max];
Arrays.fill(a, (char)0);
System.arraycopy(thisStr.toCharArray(), 0, a, 0, thisStr.length());
char[] b = new char[max];
Arrays.fill(b, (char)0);
System.arraycopy(otherStr.toCharArray(), 0, b, 0, otherStr.length());
//遍历索引位置的字符,知道找到索引位置
//字符不相等的位置
while(a[index] == b[index])
{
//如果该索引处字符相等,索引递增
index++;
//如果两个字符串看起来完全相等
//直接返回0
if(index == max)
{
return 0;
}
}
return a[index] - b[index];
}
}
public class A
{
public static void main(String[] args)
{
TreeSet set = new TreeSet();
System.out.println(set.add(new Drink("Coffee")));
System.out.println(set.size());
System.out.println(set.add(new Drink("Coffeea")));
System.out.println(set.size());
System.out.println(set.add(new Drink("Tea")));
System.out.println(set.size());
System.out.println(set.add(new Drink("Water")));
System.out.println(set.size());
System.out.println(set.add(new Drink("Cappuccino")));
System.out.println(set.size());
System.out.println(set.add(new Drink("Xo")));
System.out.println(set.size());
System.out.println(set.add(new Drink("Xo")));
System.out.println(set.size());
System.out.println(set.add(new Drink("Champagne")));
System.out.println(set.size());
for (Object d : set.toArray())
{
System.out.println(((Drink) d).name);
}
}
}