Chapter 16 - Exercise 17

(5) Create and test a Generator for BigDecimal, and ensure that it works with the Generated methods.


Exercise17.java



package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;
import java.math.*;

class BigDecimalGenerator implements Generator<BigDecimal>{
    BigDecimal bd=new BigDecimal(0);
    public BigDecimal next(){
        bd=bd.add(BigDecimal.ONE);
        return bd;
    }
}

public class Exercise17 {
    public static void main(String[] args) {
        BigDecimal[] bda=Generated.array(BigDecimal.class,new BigDecimalGenerator(),10);
        System.out.println(Arrays.toString(bda));
    }
}


Generated.java



package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;
import java.lang.reflect.*;

public class Generated{
    
    //给一个数组一个generator,我填充数组
    public static <T> T[] array(T[] ta, Generator<T> gen){
        for(int i=0;i<ta.length;i++){
            ta[i]=gen.next();
        }
        return ta;
    }
    
    
    //给我一个class文件,一个generator,我填充数组
    @SuppressWarnings("unchecked")
    public static <V> V[] array(Class<V> c, Generator<V> gen, int size){
        V[] v=(V[])Array.newInstance(c,size);
        for(int i=0;i<size;i++){
            v[i]=gen.next();
        }
        return v;
    }
}



Need Java Developers? Hire Me »

I know Java. Talk is cheap, watch my code.

I live in CANADA now.