ThinkingInJava习题-用Linkedlist作为底层实现,定义你自己的SortedSet

本文介绍了如何使用LinkedList实现自定义SortedSet类,并通过实例展示了如何操作。同时,探讨了如何利用PriorityQueue进行随机整数排序和生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()+" ");
        }
    }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值