Java编程思想第四版第十一章习题(下)

这篇博客探讨了Java编程中关于Command类的设计,包括实现一个包含String域和operation()方法的Command类,以及如何使用Command对象填充Queue并在不同类间交互。此外,还涉及PriorityQueue的使用,如填充Double值并进行排序。文章中还提到一些编程挑战,如使类适应Collection接口和实现Iterable接口,以及添加reversed()和randomized()方法。作者鼓励读者尝试这些练习,并提供了联系方式以解答疑问。

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

这是第十一章最后一节,之后我会做前11章节的回顾(按着目录捋)

题目27-32,其中30-32因为我没有源代码,所以我贴的官网答案。

编译器:IDEA

27.写一个称为Command的类,它包含一个String域和一个显示该String的operation()方法。写第二类,它具有一个使用Command对象来填充一个Queue并返回这个对象的方法。将填充后的Queue传递给第三个类的一个方法,该方法消耗掉Queue中的对象,并调用它们的operation()方法。

package job;
import java.lang.reflect.Array;
import java.util.*;
import java.util.Map.Entry;
class Command{
    String a;
    public void Operation(){
        System.out.println(a);
    }
}
class A {
    public Queue<Command> a = new LinkedList<>(
            Arrays.asList(new Command(), new Command())
    );
}
class B {
    void removea(Queue<Command> a){
        for(Command b:a){
            b.Operation();
            System.out.println(a.remove());
        }
    }
}
public class Main {
    public static void main(String[] args) {
        A a=new A();
        B b=new B();
        b.removea(a.a);
    }
}

28.用由java.util.Random创建的Double值填充一个PriorityQueue(用offer())方法,然后使用poll()移除并显示它们。

 

package job;
import java.lang.reflect.Array;
import java.util.*;
import java.util.Map.Entry;
public class Main {
    public static void main(String[] args) {
        Random rand=new Random();
        PriorityQueue<Double>a=new PriorityQueue<>();
        a.offer(rand.nextDouble());
        a.offer(rand.nextDouble());
        while (a.peek()!=null)
        System.out.println(a.poll()+" ");
    }
}

29.创建一个继承自Object的简单类,它不包含任何成员,展示你不能将这个类的多个示例成功地添加到一个PriorityQueue中。这个问题将在第17章中详细解释。

package job;
import java.lang.reflect.Array;
import java.util.*;
class A extends Object{

}
public class Main {
    public static void main(String[] args) {
        PriorityQueue<A>a=new PriorityQueue<>();
        a.offer(new A());
        a.offer(new A());
    }
}

报错!

30.修改CollectionSequeuece.java,使其不要继承AbstractCollection,而是实现Collection。


//: holding/CollectionSequence.java

import typeinfo.pets.*;

import java.util.*;

class InterfaceVsIterator {

  public static void display(Iterator<Pet> it) {

    while(it.hasNext()) {

      Pet p = it.next();

      System.out.print(p.id() + ":" + p + " ");

    }

    System.out.println();

  }

  public static void display(Collection<Pet> pets) {

    for(Pet p : pets)

      System.out.print(p.id() + ":" + p + " ");

    System.out.println();

  }	

  

}

public class Ja11_12_30

    implements Collection<Pet> {

  private Pet[] pets = Pets.createArray(8);

  public int size() { return pets.length; }

  public Iterator<Pet> iterator() {

    return new Iterator<Pet>() {

      private int index = 0;

      public boolean hasNext() {

        return index < pets.length;

      }

      public Pet next() { return pets[index++]; }

      public void remove() { // Not implemented

        throw new UnsupportedOperationException();

      }

    };

  }

  public boolean add(Pet p){throw new UnsupportedOperationException();}

  public boolean addAll(Collection<? extends Pet> c){throw new UnsupportedOperationException();} 

  public void clear() { 

		if(this.size() != 0)

		for(Pet p : pets)

			p = null;

	}

  public boolean retainAll(Collection<?> c) { 

		throw new UnsupportedOperationException();

	}

  public boolean removeAll(Collection<?> c) { 

		throw new UnsupportedOperationException();

	}

  public boolean contains(Object o) {	

		throw new UnsupportedOperationException();

	}

  public boolean isEmpty() {	

		return (this.size() == 0) ? true : false;

	}

  public boolean containsAll(Collection<?> c) { 

		throw new UnsupportedOperationException();

	}

  

  public boolean remove(Object o) { 

		throw new UnsupportedOperationException();

	}

  public Object[] toArray() {

		return pets;

	}

  public <T> T[] toArray(T[] a) {

            throw new UnsupportedOperationException();

       }

 

  public static void main(String[] args) {

    Ja11_12_30 c = new Ja11_12_30();

    InterfaceVsIterator.display(c);

    InterfaceVsIterator.display(c.iterator());

  }

} /* Output:

*///:~

 

31.修改polymorphism/shape/RandomShapeGenerator.java,使其成为一个Iterable。你需要添加一个接受元素数量为参数的构造器,这个数量是指在停止之前,你想用迭代器生成的元素的数量。验证这个程序可以工作。


/* Modify polymorphism/shape/RandomShapeGenerator.java to make it

* Iterable. You'll need to add a constructor that takes the number of

* elements that you want the iterator to produce before stopping. Verify

* that it works.

*/

import java.util.*;

import static net.mindview.util.Print.*;

 

class RandomShapeGenerator implements Iterable<Shape>{

  private Random rand = new Random(47);

  Shape[] shape;

  RandomShapeGenerator(int count){

      shape=new Shape[count];

      for(int i=0;i<shape.length;i++)shape[i]=next();

  }

  public Shape next() {

    switch(rand.nextInt(3)) {

      default:

      case 0: return new Circle();

      case 1: return new Square();

      case 2: return new Triangle();

    }

  }

  public Iterator<Shape> iterator(){

    return new Iterator<Shape>(){

        private int index=-1;

        public boolean hasNext(){return index<shape.length;}

        public Shape next(){index++;return shape[index];}

        public void remove(){throw new UnsupportedOperationException();}

    };

  

  }  

}

public class Ja11_13_31{

    public static void main(String[] args){

        RandomShapeGenerator rs=new RandomShapeGenerator(4);

        Iterator<Shape> it=rs.iterator();

        while(it.hasNext()){

            print(it.next());

            it.remove();

        }

    }

}

 

32.按照MultiIterableClass示例,在NonCollectionSequence.java中添加reversed()和randomized()方法,并让NonCollectionSequence实现Iterable。然后在foreach语句中展示所有的使用方式。


/* Following the example of MultiIterableClass, add reversed() and randomized() 

* methods to NonCollectionSequence.java, as well as making  NonCollectionSequence.java

* implement Iterable and show that all the approaches * work in foreach statements.

*/

import java.util.*;

import static net.mindview.util.Print.*;

import typeinfo.pets.*;

 

class PetSequence {

  protected Pet[] pets = Pets.createArray(8);

}

 

public class Ja11_13_32 extends PetSequence /*implements Iterable<Pet>*/ {

    public Iterable<Pet> iterator(){

        return new Iterable<Pet>(){

          public Iterator<Pet> iterator() {

            return new Iterator<Pet>() {

              private int index = 0;

              public boolean hasNext() {

                return index<pets.length;

              }

              public Pet next() { return pets[index++]; }

              public void remove() { // Not implemented

                throw new UnsupportedOperationException();

              }

            };

          }

        };

    }

    public Iterable<Pet> reversed(){

        return new Iterable<Pet>(){

          public Iterator<Pet> iterator() {

            return new Iterator<Pet>() {

              private int index = pets.length-1;

              public boolean hasNext() {

                return index>-1;

              }

              public Pet next() { return pets[index--]; }

              public void remove() { // Not implemented

                throw new UnsupportedOperationException();

              }

            };

          }

        };

    }

    public Iterable<Pet> randomized(){

        return new Iterable<Pet>(){

            public Iterator<Pet> iterator(){

                Random rand=new Random(6);

                List<Pet> lp=new ArrayList<Pet>(Arrays.asList(pets));

                Collections.shuffle(lp,rand);

                return lp.iterator();

             }

        };

    }

  public static void  display(Iterable<Pet> itb){

    for(Pet i:itb){print(i);}

  }

  public static void main(String[] args) {

    Ja11_13_32 nc = new Ja11_13_32();

    display(nc.randomized());

    print();

    display(nc.iterator());

        print();

    display(nc.reversed());

  }

}

/*Pug

Rat

Manx

Pug

Mutt

Cymric

Manx

Cymric



Rat

Manx

Cymric

Mutt

Pug

Cymric

Pug

Manx



Manx

Pug

Cymric

Pug

Mutt

Cymric

Manx

Rat*/

结束~
我的另一个博客:https://www.cnblogs.com/hsjj/
会不定时的更新算法题
有问题欢迎发送邮件至hpzhangjunjiell@163.com
我们下次见哦~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值