package chapter17;
/**
* 使用Linkedlist作为底层实现,定义你自己的SortedSet
*
* */
import java.util.*;
import static net.mindview.util.Print.*;
class SortedSet10<E> extends LinkedList<E> {
int compare(E e1, E e2) {
int c = e1.hashCode() - e2.hashCode();
return (c < 0) ? -1 : ((c == 0) ? 0 : 1);
}
public boolean add(E e) {
if(!this.contains(e)) {
Iterator<E> it = this.iterator();
int index = 0;
while(it.hasNext()) {
if(compare(it.next(), e) < 1)
index++;
}
add(index, e);
return true;
}
return false;
}
}
class T {}
public class Ex10{
public static void main(String[] args) {
SortedSet10<T> ss = new SortedSet10<T>();
ss.add(new T());
ss.add(new T());
ss.add(new T());
ss.add(new T());
print(ss);
SortedSet10<Integer> ss2 = new SortedSet10<Integer>();
ss2.add(6);
ss2.add(8);
ss2.add(2);
ss2.add(4);
ss2.add(2);
ss2.add(8);
print(ss2);
SortedSet10<String> ss3 = new SortedSet10<String>();
ss3.add("three");
ss3.add("three");
ss3.add("seven");
ss3.add("hi");
ss3.add("two");
ss3.add("one");
print(ss3);
}
}
package chapter17;
import java.util.PriorityQueue;
import java.util.Random;
/**
* 创建一个类 包含integer 其值通过java.util.random初始化为0-100之间的值,
* integer域实现Comparable 用这个类的对象来填充PriorityQueue 在使用poll
* 抽取这些值来展示该队列按照我们预期的顺序产生这些值
* */
// integer初始化值 实现compareable接口
class IntegerTest implements Comparable<IntegerTest>{
Integer a=new Random().nextInt(100);
@Override
public int compareTo(IntegerTest o) {
int d=this.a-o.a;
return d<0 ? -1: d==0 ? 0 :1;
}
public String toString(){
return Integer.toString(a);
}
}
public class Ex11 extends PriorityQueue<IntegerTest> {
public void add(){
super.add(new IntegerTest());
}
public static void main(String[] args) {
PriorityQueue<IntegerTest> pt=
new PriorityQueue<IntegerTest>();
for(int i=0;i<20;i++){
pt.add(new IntegerTest());
}
int size=pt.size();
for(int i=0;i<size;i++){
System.out.print(pt.poll()+" ");
}
}
}
ThinkingInJava习题-用Linkedlist作为底层实现,定义你自己的SortedSet
于 2022-02-26 15:10:21 首次发布