Java编程思想第四版第十五章习题(终篇)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java编程思想第四版第十五章习题(终篇),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含8691字,纯文字阅读大概需要13分钟。
内容图文
40 Add a speak() method to all the pets in tyepinfo.pets. Modify Apply.java to call the speakmethod for a heterogeneous collection of Pet.
package job;
import java.lang.reflect.*;
import java.util.*;
import static net.mindview.util.Print.*;
import typeinfo.pets.*;
class Apply {
public static <T, S extends Iterable<? extends T>>
void apply(S seq, Method f, Object... args) {
try {
for (T t : seq)
f.invoke(t, args);
} catch (Exception e) {
// Failures are programmer errors
throw new RuntimeException(e);
}
}
}
class Shape {
public void rotate() {
System.out.println(this + " rotate");
}
public void resize(int newSize) {
System.out.println(this + " resize " + newSize);
}
}
class Square extends Shape {}
class FilledList<T> extends ArrayList<T> {
public FilledList(Class<? extends T> type, int size) {
try {
for (int i = 0; i < size; i++)
// Assumes default constructor:
add(type.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class Main {
public static void main(String[] args) throws Exception {
List<Shape> shapes = new ArrayList<Shape>();
for (int i = 0; i < 10; i++)
shapes.add(new Shape());
Apply.apply(shapes, Shape.class.getMethod("rotate"));
Apply.apply(shapes,
Shape.class.getMethod("resize", int.class), 5);
List<Square> squares = new ArrayList<Square>();
for (int i = 0; i < 10; i++)
squares.add(new Square());
Apply.apply(squares, Shape.class.getMethod("rotate"));
Apply.apply(squares,
Shape.class.getMethod("resize", int.class), 5);
Apply.apply(new FilledList<Shape>(Shape.class, 10),
Shape.class.getMethod("rotate"));
Apply.apply(new FilledList<Shape>(Square.class, 10),
Shape.class.getMethod("rotate"));
List<Pet> lp = new ArrayList<Pet>();
lp.add(new Dog());
lp.add(new Cat());
lp.add(new Pug());
Apply.apply(lp, Pet.class.getMethod("speak"));
}
}
41 Modify Fill2.java to use the classes in typeinfo.pets instead of the Pet classes.
package job;
import generics.coffee.*;
import java.util.*;
import net.mindview.util.*;
import typeinfo.pets.*;
interface Addable<T> { void add(T t); }
class SimpleQueue<T> implements Iterable<T> {
private LinkedList<T> storage = new LinkedList<T>();
public void add(T t) {
storage.offer(t);
}
public T get() {
return storage.poll();
}
public Iterator<T> iterator() {
return storage.iterator();
}
}
class Fill2 {
public static <T> void fill(Addable<T> addable,
Class<? extends T> classToken, int size) {
for (int i = 0; i < size; i++)
try {
addable.add(classToken.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
class AddableCollectionAdapter<T> implements Addable<T> {
private Collection<T> c;
public AddableCollectionAdapter(Collection<T> c) {
this.c = c;
}
public void add(T item) {
c.add(item);
}
}
class Adapter {
public static <T>
Addable<T> collectionAdapter(Collection<T> c) {
return new AddableCollectionAdapter<T>(c);
}
}
class AddableSimpleQueue<T>
extends SimpleQueue<T> implements Addable<T> {
public void add(T item) {
super.add(item);
}
}
public class Main {
public static void main(String[] args) {
// Adapt a Collection:
List<Pet> carrier = new ArrayList<Pet>();
Fill2.fill(
new AddableCollectionAdapter<Pet>(carrier),
Pet.class, 3);
Fill2.fill(Adapter.collectionAdapter(carrier),
Dog.class, 2);
for (Pet c : carrier)
System.out.println(c);
System.out.println("----------------------");
// Use an adapted class:
AddableSimpleQueue<Pet> coffeeQueue =
new AddableSimpleQueue<Pet>();
Fill2.fill(coffeeQueue, Pug.class, 4);
Fill2.fill(coffeeQueue, Dog.class, 1);
for (Pet c : coffeeQueue)
System.out.println(c);
}
}
42 Create two separate classes, with nothing in common. Each class should hold a value, and at least have methods that produce that value and perform a modification upon that value. Modify Functional.java so that it performs functional operations on collections of your classes (these operations do not have to be arithmetic as they are in Functional.java).
package job;
import typeinfo.pets.*;
import java.math.*;
import java.util.concurrent.atomic.*;
import java.util.*;
interface Combiner<T> {
T combine(T x, T y);
}
interface UnaryFunction<R,T> {
R function(T x);
}
interface Collector<T> extends UnaryFunction<T,T> {
T result();
}
interface UnaryPredicate<T> { boolean test(T x); }
class A implements UnaryPredicate<Pet>{
public boolean test(Pet p){return p.getClass().getSimpleName().equals("Pet");};
}
class B implements UnaryPredicate<Dog> {
public boolean test(Dog p) {
return p.getClass().getSimpleName().equals("Dog");
}
;
}
public class Main {
// Calls the Combiner object on each element to combine
// it with a running result, which is finally returned:
public static <T> T
reduce(Iterable<T> seq, Combiner<T> combiner) {
Iterator<T> it = seq.iterator();
if (it.hasNext()) {
T result = it.next();
while (it.hasNext())
result = combiner.combine(result, it.next());
return result;
}
// If seq is the empty list:
return null; // Or throw exception
}
// Take a function object and call it on each object in
// the list, ignoring the return value. The function
// object may act as a collecting parameter, so it is
// returned at the end.
public static <T> Collector<T>
forEach(Iterable<T> seq, Collector<T> func) {
for (T t : seq)
func.function(t);
return func;
}
// Creates a list of results by calling a
// function object for each object in the list:
public static <R, T> List<R>
transform(Iterable<T> seq, UnaryFunction<R, T> func) {
List<R> result = new ArrayList<R>();
for (T t : seq)
result.add(func.function(t));
return result;
}
// Applies a unary predicate to each item in a sequence,
// and returns a list of items that produced "true":
public static <T> List<T>
filter(Iterable<T> seq, UnaryPredicate<T> pred) {
List<T> result = new ArrayList<T>();
for (T t : seq)
if (pred.test(t))
result.add(t);
return result;
}
// To use the above generic methods, we need to create
// function objects to adapt to our particular needs:
static class IntegerAdder implements Combiner<Integer> {
public Integer combine(Integer x, Integer y) {
return x + y;
}
}
static class
IntegerSubtracter implements Combiner<Integer> {
public Integer combine(Integer x, Integer y) {
return x - y;
}
}
static class
BigDecimalAdder implements Combiner<BigDecimal> {
public BigDecimal combine(BigDecimal x, BigDecimal y) {
return x.add(y);
}
}
static class
BigIntegerAdder implements Combiner<BigInteger> {
public BigInteger combine(BigInteger x, BigInteger y) {
return x.add(y);
}
}
static class
AtomicLongAdder implements Combiner<AtomicLong> {
public AtomicLong combine(AtomicLong x, AtomicLong y) {
// Not clear whether this is meaningful:
return new AtomicLong(x.addAndGet(y.get()));
}
}
// We can even make a UnaryFunction with an "ulp"
// (Units in the last place):
static class BigDecimalUlp
implements UnaryFunction<BigDecimal, BigDecimal> {
public BigDecimal function(BigDecimal x) {
return x.ulp();
}
}
static class GreaterThan<T extends Comparable<T>>
implements UnaryPredicate<T> {
private T bound;
public GreaterThan(T bound) {
this.bound = bound;
}
public boolean test(T x) {
return x.compareTo(bound) > 0;
}
}
static class MultiplyingIntegerCollector
implements Collector<Integer> {
private Integer val = 1;
public Integer function(Integer x) {
val *= x;
return val;
}
public Integer result() {
return val;
}
}
public static void main(String[] args) {
// Generics, varargs & boxing working together:
List<Integer> li = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
Integer result = reduce(li, new IntegerAdder());
System.out.println(result);
result = reduce(li, new IntegerSubtracter());
System.out.println(result);
System.out.println(filter(li, new GreaterThan<Integer>(4)));
System.out.println(forEach(li,
new MultiplyingIntegerCollector()).result());
System.out.println(forEach(filter(li, new GreaterThan<Integer>(4)),
new MultiplyingIntegerCollector()).result());
MathContext mc = new MathContext(7);
List<BigDecimal> lbd = Arrays.asList(
new BigDecimal(1.1, mc), new BigDecimal(2.2, mc),
new BigDecimal(3.3, mc), new BigDecimal(4.4, mc));
BigDecimal rbd = reduce(lbd, new BigDecimalAdder());
System.out.println(rbd);
System.out.println(filter(lbd,
new GreaterThan<BigDecimal>(new BigDecimal(3))));
// Use the prime-generation facility of BigInteger:
List<BigInteger> lbi = new ArrayList<BigInteger>();
BigInteger bi = BigInteger.valueOf(11);
for (int i = 0; i < 11; i++) {
lbi.add(bi);
bi = bi.nextProbablePrime();
}
System.out.println(lbi);
BigInteger rbi = reduce(lbi, new BigIntegerAdder());
System.out.println(rbi);
// The sum of this list of primes is also prime:
System.out.println(rbi.isProbablePrime(5));
List<AtomicLong> lal = Arrays.asList(
new AtomicLong(11), new AtomicLong(47),
new AtomicLong(74), new AtomicLong(133));
AtomicLong ral = reduce(lal, new AtomicLongAdder());
System.out.println(ral);
System.out.println(transform(lbd, new BigDecimalUlp()));
List<Pet> lp = Arrays.asList(new Pet());
System.out.println(filter(lp, new A()));
List<Dog> lg = Arrays.asList(new Dog());
System.out.println(filter(lg, new B()));
}
}
内容总结
以上是互联网集市为您收集整理的Java编程思想第四版第十五章习题(终篇)全部内容,希望文章能够帮你解决Java编程思想第四版第十五章习题(终篇)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。