2016-09-05 13:34:49 +0000   |     java thinking in java data structure array   |   Viewed times   |    

数组好在哪儿?

数组的优点,不能和现在的泛型容器比。要和它同时期的无泛型的原生容器比。站在Java1.0的时间基准上看,数组至少有三大优势:

但现在有泛型容器,也已经编译器类型检查。而且直接有“自动包装机制”,容器持有基本型不成问题。数组只剩下高效一个优点了。但因为数组有长度限制,而且容器功能更多。所以现在普遍都用容器。

数组的初始化

数组初始化的三种层次:

        /**
         *  对象数组
         */
        //未初始化
        AAA[] a;
        //常见的创建特定类型和长度的空数组。每个槽位自动初始化为null。
        AAA[] b=new AAA[5];
        AAA[] c=new AAA[] {aaa1,aaa2,aaa3};

        /**
         *  基本型数组
         */
        //未初始化
        int[] e;
        //常见[]下标创建空数组。每个槽位都默认被初始化为0。
        int[] f = new int[5];
        // 直接用大括号{}赋值。第一种只能用在定义数组的地方。第二种哪里都可以用。
        int[] g = { 11, 47, 93 };
        int[] h= new int[]{ 1, 2 };

多维数组

多维数组的初始化和普通数组差不多。

int[][] a = {
	{ 1, 2, 3, },
	{ 4, 5, 6, },
};

多维数组也可以一维一维地创建。

int[][] a = new int[5][];

for(int i=0;i<a.length;i++){
	a[i]=new int[6];
}

没有被完整定义长度的多维数组,会自动被初始化成null。

int[][][] two=new int[2][][];
int[][][] three=new int[2][3][];
int[][][] four=new int[2][3][4];

two和three两个数组,只定义了第一层,和第二层的长度。打印出来,全都是null。只有four数组,三层长度都定义了,所有元素都被初始化成0。

System.out.println(Arrays.deepToString(two));
System.out.println(Arrays.deepToString(three));
System.out.println(Arrays.deepToString(four));

//Output:
//[null, null]
//[[null, null, null], [null, null, null]]
//[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

数组的协变

数组的协变要注意的一点是:

虽然依据协变原则,对象数组Object[]里可以插入String对象实例。

Object[] o=new Object[1];
o[0]=new String("hello");

也可以直接把String[]的引用赋给Object[]。

Object[] o=new Object[1];
String[] s=new String[5];
o=s;

但我们不能把Object[]向下转型成String[]。

String[] s=(String[])new Object[1];

因为,“协变”特性的本质是:当B类是A类的派生类,B[]也是A[]的派生类

所以String[]是Object[]的派生类。但强制向下转型是不允许的。

数组和泛型

Java不允许创建泛型类的数组:

Bag<Banana>[] bagB=new Bag<Banana>[10];		//Error

但可以用类型参数表示数组本身的类型,像这样:

class Bag<T>{
	private T[] items;
}

这样的T[]在运行时都被擦除成Object[]。要初始化这样的数组items,最好的办法是,先创建一个擦除以后的类型的数组,比如这里是Object,然后在用T[]强制转型。

class Bag<T>{
	private T[] items;
	public Bag(int size){
		items=(T[])new Object[size];
	}
}

因为运行时T[]都会被擦除,变成Object[],所以这里的强制转型只是在编译期起作用。而且会抛出一个[unchecked]的警告。

填充数组

####Arrays.fill() 标准类库的fill()只能用同一个值填充每个槽位。

int[] i=new int[10];
Arrays.fill(i,9);

填完的效果是:

[9,9,9,9,9,9,9,9,9,9]

书里花很大力气讲了怎么用泛型Generator写一个更强大的自动填充工具,这里不赘述。具体实现,参见练习题11-17。我已经完整地自己实现了一遍。

Arrays实用工具

拷贝数组

System.arraycopy()

Java标准类库提供的拷贝数组的 “高效” 方法。负责把一段数组拷贝到另一个数组的某个位置。看下面的例子,

int[] i=new int[7];
int[] j=new int[10];
Arrays.fill(i,47);
Arrays.fill(j,99);

System.arraycopy(i,0,j,0,i.length);

上面这个拷贝操作,翻译过来就是:从i数组的第一个元素开始,拷贝到j数组的第一个槽位,以此类推,直到i数组的最后一个元素。拷贝完的结果是这样的:

[47,47,47,47,47,47,47,99,99,99]
Arrays.copyOf()

标准类库还包含两个拷贝数组的方法:Arrays.copyOf()和Object.clone()。

int[] ia={9,9,9,9,9,9,9,9,9,9};
int[] copy=Arrays.copyOf(ia,20);

Arrays.copyOf()接受两个参数,第一个是源数组,第二个拷贝以后数组的长度。可以用来扩展数组。用起来比System.arraycopy()简便,但功能弱一些。例子里的拷贝的结果是:

[9,9,9,9,9,9,9,9,9,9,0,0,0,0,0,0,0,0,0,0]
Object.clone()

最后一个Object.clone()功能最弱,只能单纯地拷贝数组。

int[] ia={9,9,9,9,9,9,9,9,9,9};
copy=ia.clone();

《Effective Java》里说:

数组的比较

java.lang.Comparable接口

第一种是实现 java.lang.Comparable 接口。它只规定了 compareTo(Object o) 一个方法。实现了Comparable接口的类型都可以实现排序,也就是 Arrays.sort() 方法。

class CompType implements Comparable{
	private int i;
	public CompType(int inNum){i=inNum;}

	public int compareTo(CompType rv){
		return (i < rv.i ? -1 : (i == rv.i ? 0 : 1));
	}

	public static void main(){
		CompType[] ct={new CompType(10), new CompType(5)};
		Arrays.sort(ct);
	}
}

Object1.compareTo(Object2)方法返回值小于零,等于零,大于零,分别表示Object1小于,等于,大于Object2。

Comparator接口

如果要比较的类没有实现Comparable接口。可以另外写一个实现了Comparator接口的“比较器”。然后排序的时候,调用Arrays.sort()方法的另一个重载版本:Arrays.sort(T[] a, Comparator<? super T> c)。就是利用外部的比较器来实现比较。利用的是“策略模式”。

Comparator接口要求实现两个方法:compare()equals()。compare()方法原理和compareTo()方法一样。equals()方法只要用继承自Object基类的原始版本就行,所以不用重写。

数组搜索

排序过的数组可以调用Arrays.binarySearch()方法。

练习

Exercise 1

class CallArray{
    public static void showArray(String[] s){
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<s.length;i++){
            sb.append("{").append(ss[i]).append("}");
            if(i<s.length-1){
                sb.append("--");
            }
        }
        System.out.println(sb.toString());
    }
}
public class Exercise1{
    public static void main(String[] args){
        //CallArray.showArray({"AAA","BBB","CCC"});
        CallArray.showArray(new String[]{"AAA","BBB","CCC"});
    }
}

Exercise 2

class Sphere{
    private static int count=0;
    private int id=++count;
    public String toString(){return "Sphere "+id;}
}

public class Exercise2{
    public static Sphere[] collectSphere(int i){
        Sphere[] s=new Sphere[i];
        for(int j=0;j<i;j++){
            s[j]=new Sphere();
        }
        return s;
    }

    public static void printSpheres(Sphere[] ss){
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<ss.length;i++){
            sb.append("{").append(ss[i]).append("}");
            if(i<ss.length-1){
                sb.append("--");
            }
        }
        System.out.println(sb);
    }
    public static void main(String[] args){
        Exercise2.printSpheres(Exercise2.collectSphere(7));


    }
}

Exercise 3

public class Exercise3{

    public static Double[][] makeDoubleArray(int x,int y,int min,int max){
        Random rand=new Random();
        Double[][] d=new Double[x][y];
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                d[i][j]=(double)min+(max-min)*rand.nextDouble();
            }
        }
        return d;
    }

    public static void printArray(Double[][] d){
        System.out.println(Arrays.deepToString(d));
    }

    public static void main(String[] args){
        Exercise3.printArray(Exercise3.makeDoubleArray(2,3,0,100));
    }
}

Exercise 4

public class Exercise4{

    public static Double[][][] makeDoubleArray(int x,int y,int z,int min,int max){
        Random rand=new Random();
        Double[][][] d=new Double[x][y][z];
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                for(int k=0;k<z;k++){
                    d[i][j][k]=(double)min+(max-min)*rand.nextDouble();
                }
            }
        }
        return d;
    }

    public static void printArray(Double[][][] d){
        System.out.println(Arrays.deepToString(d));
    }

    public static void main(String[] args){
        Exercise4.printArray(Exercise4.makeDoubleArray(2,3,2,0,100));
    }
}

Exercise 5

public class Exercise5{
    public static void main(String[] args){
        int[][][] one;
        int[][][] two=new int[2][][];
        int[][][] three=new int[2][3][];
        int[][][] four=new int[2][3][4];

        //System.out.println(Arrays.deepToString(one)); //没有初始化
        System.out.println(Arrays.deepToString(two));
        System.out.println(Arrays.deepToString(three));
        System.out.println(Arrays.deepToString(four));
    }
}

Exercise 6

class Sphere{
    private static int count=0;
    private int id=++count;
    public String toString(){return "Sphere "+id;}
}

public class Exercise6{
    public static Sphere[][] fill2DSphere(int x,int y){
        Sphere[][] s=new Sphere[x][y];
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                s[i][j]=new Sphere();
            }
        }
        return s;
    }

    public static void main(String[] args){
        System.out.println(Arrays.deepToString(Exercise6.fill2DSphere(3,4)));


    }
}

Exercise 7

class Sphere{
    private static int count=0;
    private int id=++count;
    public String toString(){return "Sphere "+id;}
}

public class Exercise7{
    public static Sphere[][][] fill3DSphere(int x,int y,int z){
        Sphere[][][] s=new Sphere[x][y][z];
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++){
                for(int k=0;k<z;k++){
                    s[i][j][k]=new Sphere();
                }
            }
        }
        return s;
    }

    public static void main(String[] args){
        System.out.println(Arrays.deepToString(Exercise7.fill3DSphere(3,4,5)));
    }
}

Exercise 8

class ArrayOfGenericType<T> {
    T[] array;
    @SuppressWarnings("unchecked")
    public ArrayOfGenericType(int size){
        array=(T[])new Object[size];
    }

    public void insertFirst(T t){
        array[0]=t;
    }

    @SuppressWarnings("unchecked")
    public <U> U[] makeArray() { return (U[])new Object[10]; }
}

public class Exercise8{
    public static void main(String[] args){
        ArrayOfGenericType<String> agt=new ArrayOfGenericType<String>(10);
        agt.insertFirst("Hello");
        Object[] str=agt.makeArray();
    }
}

Exercise 9

class Peel<T>{}

class Banana{}

public class Exercise9{
    public static void main(String[] args){
        //Peel<Banana>[] pb=new Peel<Banana>[10];
        ArrayList<Peel<Banana>> apb=new ArrayList<Peel<Banana>>();
    }
}

Exercise 10

class ArrayOfGenericType<T> {
    List<T> array;
    public ArrayOfGenericType() {
        array = new ArrayList<T>();
    }
}

public class Exercise10{
    public static void main(String[] args){
        ArrayOfGenericType<String> agt=new ArrayOfGenericType<String>();
    }
}

Exercise 11

public class Exercise11{
    public static void main(String[] args){
        int[] i=new int[]{1,2,3,4,5};
        Integer ii=i;
    }
}

Exercise 12

public class Exercise12{
    public static void main(String[] args){
        CountingGenerator.Double genD=new CountingGenerator.Double();
        double[] d=new double[10];
        for(int i=0;i<10;i++){
            d[i]=genD.next();
        }
        for(int i=0;i<10;i++){
            System.out.print(d[i]+" ");
        }
    }
}

Exercise 13

public class Exercise13{
    public static void main(String[] args){
        CountingGenerator.Character genC=new CountingGenerator.Character();
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<10;i++){
            sb.append(genC.next());
        }
        String s=sb.toString();
        System.out.println(s);
    }
}

Exercise 14

public class PrimConv{
        public static boolean[] toPrim(Boolean[] ba){
            boolean[] b=new boolean[ba.length];
            for(int j=0;j<ba.length;j++){
                b[j]=ba[j];
            }
            return b;
        }

        public static int[] toPrim(Integer[] ia){
            int[] i=new int[ia.length];
            for(int j=0;j<ia.length;j++){
                i[j]=ia[j];
            }
            return i;
        }

        public static long[] toPrim(Long[] la){
            long[] l=new long[la.length];
            for(int j=0;j<la.length;j++){
                l[j]=la[j];
            }
            return l;
        }

        public static short[] toPrim(Short[] sa){
            short[] s=new short[sa.length];
            for(int j=0;j<sa.length;j++){
                s[j]=sa[j];
            }
            return s;
        }

        public static float[] toPrim(Float[] fa){
            float[] f=new float[fa.length];
            for(int j=0;j<fa.length;j++){
                f[j]=fa[j];
            }
            return f;
        }

        public static double[] toPrim(Double[] da){
            double[] d=new double[da.length];
            for(int j=0;j<da.length;j++){
                d[j]=da[j];
            }
            return d;
        }

        public static byte[] toPrim(Byte[] ba){
            byte[] b=new byte[ba.length];
            for(int j=0;j<ba.length;j++){
                b[j]=ba[j];
            }
            return b;
        }

        public static char[] toPrim(Character[] ca){
            char[] c=new char[ca.length];
            for(int j=0;j<ca.length;j++){
                c[j]=ca[j];
            }
            return c;
        }
}

public class Exercise14{
    public static void main(String[] args){
        CountingGenerator.Boolean b=new CountingGenerator.Boolean();
        CountingGenerator.Integer ii=new CountingGenerator.Integer();
        CountingGenerator.Long l=new CountingGenerator.Long();
        CountingGenerator.Short s=new CountingGenerator.Short();
        CountingGenerator.Float f=new CountingGenerator.Float();
        CountingGenerator.Double d=new CountingGenerator.Double();
        CountingGenerator.Byte bt=new CountingGenerator.Byte();
        CountingGenerator.Character c=new CountingGenerator.Character();

        Boolean[] bb=new Boolean[10];
        Integer[] iii=new Integer[10];
        Long[] ll=new Long[10];
        Short[] ss=new Short[10];
        Float[] ff=new Float[10];
        Double[] dd=new Double[10];
        Byte[] btbt=new Byte[10];
        Character[] cc=new Character[10];

        boolean[] ba=new boolean[10];
        int[] ia=new int[10];
        long[] la=new long[10];
        short[] sa=new short[10];
        float[] fa=new float[10];
        double[] da=new double[10];
        byte[] bta=new byte[10];
        char[] ca=new char[10];

        for(int i=0;i<10;i++){
            bb[i]=b.next();
            iii[i]=ii.next();
            ll[i]=l.next();
            ss[i]=s.next();
            ff[i]=f.next();
            dd[i]=d.next();
            btbt[i]=bt.next();
            cc[i]=c.next();
        }


        ba=PrimConv.toPrim(bb);
        ia=PrimConv.toPrim(iii);
        la=PrimConv.toPrim(ll);
        sa=PrimConv.toPrim(ss);
        fa=PrimConv.toPrim(ff);
        da=PrimConv.toPrim(dd);
        bta=PrimConv.toPrim(btbt);
        ca=PrimConv.toPrim(cc);

        for(int i=0;i<10;i++){
            System.out.print(ba[i]);
        }
        System.out.println("");
        for(int i=0;i<10;i++){
            System.out.print(ia[i]);
        }
        System.out.println("");
        for(int i=0;i<10;i++){
            System.out.print(la[i]);
        }
        System.out.println("");
        for(int i=0;i<10;i++){
            System.out.print(sa[i]);
        }
        System.out.println("");
        for(int i=0;i<10;i++){
            System.out.print(fa[i]);
        }
        System.out.println("");
        for(int i=0;i<10;i++){
            System.out.print(da[i]);
        }
        System.out.println("");
        for(int i=0;i<10;i++){
            System.out.print(bta[i]);
        }
        System.out.println("");
        for(int i=0;i<10;i++){
            System.out.print(ca[i]);
        }
    }
}

Exercise 15

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

public class Sphere{
    private static int count=0;
    private int id=++count;
    public String toString(){return "Sphere "+id;}
}
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;
    }

    /**
     *  测试
     */
    public static void main(String[] args){
        String[] ss=new String[10];
        Generated.array(ss, new CountingGenerator.String());
        for(int i=0;i<ss.length;i++){
            System.out.println(ss[i]);
        }

        String[] sss=Generated.array(String.class,new CountingGenerator.String(),10);
        for(int i=0;i<sss.length;i++){
            System.out.println(sss[i]);
        }
    }
}
Exercise15.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

class ContainerComparison {
    public static class SphereGenerator implements Generator<Sphere>{
        public Sphere next(){
            return new Sphere();
        }
    }
}

public class Exercise15{
    public static void main(String[] args){
        ContainerComparison.SphereGenerator sg=new ContainerComparison.SphereGenerator();
        Sphere[] ss=Generated.array(Sphere.class,sg,10);
        for(Sphere s:ss){
            System.out.println(s);
        }
    }
}

Exercise 16

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


public class SkipGenerator{
    private int size=1;

    public SkipGenerator(){}
    public SkipGenerator(int size){
        this.size=size;
    }

    //Boolean
    public class Boolean implements Generator<java.lang.Boolean>{
        private boolean b=false;
        public java.lang.Boolean next(){
            if(size%2==1){
                b=!b;
            }
            return b;
        }
    }
    //Integer
    public class Integer implements Generator<java.lang.Integer>{
        private int i=0;
        public java.lang.Integer next(){
            i+=size;
            return i;
        }
    }
    //Long
    public class Long implements Generator<java.lang.Long>{
        private long l=0l;
        public java.lang.Long next(){
            l+=(long)size;
            return l;
        }
    }
    //Short
    public class Short implements Generator<java.lang.Short>{
        private short s=0;
        public java.lang.Short next(){
            s+=(short)size;
            return s;
        }
    }
    //Float
    public class Float implements Generator<java.lang.Float>{
        private float f=0f;
        public java.lang.Float next(){
            f+=(float)size;
            return f;
        }
    }
    //Double
    public class Double implements Generator<java.lang.Double>{
        private double d=0.0;
        public java.lang.Double next(){
            d+=(double)size;
            return d;
        }
    }
    //Byte
    public class Byte implements Generator<java.lang.Byte>{
        private byte b=0;
        public java.lang.Byte next(){
            b+=size;
            return b;
        }
    }

    //Charactor
    private static final char[] CS=("abcdefghijklmnopqrstuvwxyz"+"ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
    public class Character implements Generator<java.lang.Character>{
        private int index=0;
        public java.lang.Character next(){
            return CS[(index+size)%CS.length];
        }
    }


    //String
    public class String implements Generator<java.lang.String>{
        private int num=7;
        private Generator<java.lang.Character> c=new Character();
        public String(){}
        public String(int size){num=size;}
        public java.lang.String next(){
            StringBuilder sb=new StringBuilder();
            for(int i=0;i<num;i++){
                sb.append(c.next());
            }
            return sb.toString();
        }
    }
}
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;
    }
}
PrimConv.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class PrimConv{
        public static boolean[] toPrim(Boolean[] ba){
            boolean[] b=new boolean[ba.length];
            for(int j=0;j<ba.length;j++){
                b[j]=ba[j];
            }
            return b;
        }

        public static int[] toPrim(Integer[] ia){
            int[] i=new int[ia.length];
            for(int j=0;j<ia.length;j++){
                i[j]=ia[j];
            }
            return i;
        }

        public static long[] toPrim(Long[] la){
            long[] l=new long[la.length];
            for(int j=0;j<la.length;j++){
                l[j]=la[j];
            }
            return l;
        }

        public static short[] toPrim(Short[] sa){
            short[] s=new short[sa.length];
            for(int j=0;j<sa.length;j++){
                s[j]=sa[j];
            }
            return s;
        }

        public static float[] toPrim(Float[] fa){
            float[] f=new float[fa.length];
            for(int j=0;j<fa.length;j++){
                f[j]=fa[j];
            }
            return f;
        }

        public static double[] toPrim(Double[] da){
            double[] d=new double[da.length];
            for(int j=0;j<da.length;j++){
                d[j]=da[j];
            }
            return d;
        }

        public static byte[] toPrim(Byte[] ba){
            byte[] b=new byte[ba.length];
            for(int j=0;j<ba.length;j++){
                b[j]=ba[j];
            }
            return b;
        }

        public static char[] toPrim(Character[] ca){
            char[] c=new char[ca.length];
            for(int j=0;j<ca.length;j++){
                c[j]=ca[j];
            }
            return c;
        }

    public static void main(String[] args){

    }
}
Exercise16.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class Exercise16 {
    public static void main(String[] args) {
        int size=6;
        SkipGenerator sg=new SkipGenerator(2);
        boolean[] a1 = PrimConv.toPrim(Generated.array(Boolean.class, sg.new Boolean(), size));
        System.out.println("a1 = " + Arrays.toString(a1));
        byte[] a2 = PrimConv.toPrim(Generated.array(Byte.class, sg.new Byte(), size));
        System.out.println("a2 = " + Arrays.toString(a2));
        char[] a3 = PrimConv.toPrim(Generated.array(Character.class, sg.new Character(), size));
        System.out.println("a3 = " + Arrays.toString(a3));
        short[] a4 = PrimConv.toPrim(Generated.array(Short.class, sg.new Short(), size));
        System.out.println("a4 = " + Arrays.toString(a4));
        int[] a5 = PrimConv.toPrim(Generated.array(Integer.class, sg.new Integer(), size));
        System.out.println("a5 = " + Arrays.toString(a5));
        long[] a6 = PrimConv.toPrim(Generated.array(Long.class, sg.new Long(), size));
        System.out.println("a6 = " + Arrays.toString(a6));
        float[] a7 = PrimConv.toPrim(Generated.array(Float.class, sg.new Float(), size));
        System.out.println("a7 = " + Arrays.toString(a7));
        double[] a8 = PrimConv.toPrim(Generated.array(Double.class, sg.new Double(), size));
        System.out.println("a8 = " + Arrays.toString(a8));
    }
}

Exercise 17

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;
    }
}

Exercise 18

Sphere.java
import java.util.*;

public class Sphere{
    private static int count=0;
    private int id=++count;
    public String toString(){return "Sphere "+id;}
    public void setId(int inNum){id=inNum;}
}
Exercise18.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class Exercise18 {
    public static void main(String[] args) {
        Sphere[] sa1=Generated.array(Sphere.class,new SphereGenerator(),5);
        Sphere[] sa2=Generated.array(Sphere.class,new SphereGenerator(),10);

        System.out.println("Array 1:    "+Arrays.toString(sa1));
        System.out.println("Array 2:    "+Arrays.toString(sa2));

        //从sa1数组的2号下标的元素开始的3个元素,复制到sa2数组的5号下标开始的3个槽位。
        System.arraycopy(sa1,2,sa2,5,3);
        System.out.println("Array 2:    "+Arrays.toString(sa2));

        //把sa1数组的3号下标的元素id改成100。
        sa1[3].setId(100);
        System.out.println("Array 2:    "+Arrays.toString(sa2));
    }
}
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;
    }
}

Exercise 19

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

class EleToCompare{
    private int item;
    public EleToCompare(int n){
        item=n;
    }
    @Override
    public boolean equals(Object o){
        if(o instanceof EleToCompare){
            return this.item==((EleToCompare)o).item;
        }else{
            return false;
        }

    }
	@Override
    public int hashCode(){
        return item;
    }
}

public class Exercise19 {
    public static void main(String[] args) {
        EleToCompare[] ea1=new EleToCompare[5];
        EleToCompare[] ea2=new EleToCompare[5];

        for(int i=0;i<5;i++){
            ea1[i]=new EleToCompare(10);
            ea2[i]=new EleToCompare(10);
        }

        System.out.println(ea1[1].equals(ea2[1]));
        System.out.println(Arrays.equals(ea1,ea2));
    }
}

Exercise 20

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

public class Exercise20 {
    public static void main(String[] args) {
        EleToCompare[][] d1=new EleToCompare[3][3];
        EleToCompare[][] d2=new EleToCompare[3][3];

        for(int i=0;i<3;i++){
            Arrays.fill(d1[i],new EleToCompare(10));
            Arrays.fill(d2[i],new EleToCompare(10));
        }

        System.out.println(Arrays.deepEquals(d1,d2));
    }
}
EleToCompare.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class EleToCompare{
    private int item;
    public EleToCompare(int n){
        item=n;
    }
    @Override
    public boolean equals(Object o){
        if(o instanceof EleToCompare){
            return this.item==((EleToCompare)o).item;
        }else{
            return false;
        }

    }
    @Override
    public int hashCode(){
        return item;
    }
}

Exercise 21

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

public class Sphere{
    private static int count=0;
    private int id=++count;
    public String toString(){return "Sphere "+id;}
    public void setId(int inNum){id=inNum;}
    public int getId(){return id;}
}
SphereComparator.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class SphereComparator implements Comparator<Sphere>{

    public int compare(Sphere s1, Sphere s2){
        return s1.getId()-s2.getId();
    }

    public static void main(String[] args) {

    }
}
Exercise21.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class Exercise21 {
    public static void main(String[] args) {
        Sphere[] sa1=Generated.array(Sphere.class,new SphereGenerator(),5);
        Sphere[] sa2=Generated.array(Sphere.class,new SphereGenerator(),10);

        System.arraycopy(sa1,2,sa2,5,3);
        sa1[3].setId(100);

        //未排序前
        System.out.println("Before Sort:    "+Arrays.toString(sa2));

        Arrays.sort(sa2, new SphereComparator());

        //排序后
        System.out.println("After Sort:    "+Arrays.toString(sa2));
    }
}

Exercise 22

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

public class Exercise22 {
    public static void main(String[] args) {
        Sphere[] sa1=Generated.array(Sphere.class,new SphereGenerator(),5);
        Sphere[] sa2=Generated.array(Sphere.class,new SphereGenerator(),10);

        System.arraycopy(sa1,2,sa2,5,3);
        sa1[3].setId(100);

        //未排序前
        System.out.println("Before Sort:    "+Arrays.toString(sa2));
        System.out.println(Arrays.binarySearch(sa2,sa2[5],new SphereComparator()));

        //排序后
        Arrays.sort(sa2, new SphereComparator());
        System.out.println("After Sort:    "+Arrays.toString(sa2));
        System.out.println(Arrays.binarySearch(sa2,sa2[5],new SphereComparator()));
    }
}
SphereComparator.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class SphereComparator implements Comparator<Sphere>{

    public int compare(Sphere s1, Sphere s2){
        return s1.getId()-s2.getId();
    }

    public static void main(String[] args) {

    }
}

Exercise 23

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

public class Exercise23 {
    public static void main(String[] args) {
        Integer[] ia=new Integer[10];
        Random rand=new Random();
        for(int i=0;i<ia.length;i++){
            ia[i]=rand.nextInt(10000);
        }

        Arrays.sort(ia, Collections.reverseOrder());
        System.out.println(Arrays.toString(ia));
    }
}

Exercise 24

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

public class EleToCompare{
    private int item;
    public EleToCompare(int n){
        item=n;
    }
    public int getItem(){return item;}
    @Override
    public boolean equals(Object o){
        if(o instanceof EleToCompare){
            return this.item==((EleToCompare)o).item;
        }else{
            return false;
        }

    }
    @Override
    public int hashCode(){
        return item;
    }
}
EleToComparaComparator.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class EleToCompareComparator implements Comparator<EleToCompare>{
    public int compare(EleToCompare e1, EleToCompare e2){
        return e1.getItem()-e2.getItem();
    }
}
Exercise24.java
package com.ciaoshen.thinkinjava.chapter16;
import java.util.*;

public class Exercise24 {
    public static void main(String[] args) {
        EleToCompare[] ea1=new EleToCompare[10];

        for(int i=0;i<ea1.length;i++){
            ea1[i]=new EleToCompare(i);
        }

        Arrays.sort(ea1,new EleToCompareComparator());
        System.out.println(Arrays.binarySearch(ea1,new EleToCompare(6),new EleToCompareComparator()));
    }
}

Exercise 25

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

public class Exercise25 {
    public static void main(String[] args) {
        int[] i={1,2,3,4,5};
        System.out.println(i.getClass());
        System.out.println(Arrays.toString(i));
        System.out.println(i[4]);
        int[] i2=new int[6];
        System.arraycopy(i,0,i2,0,i.length);
        i2[5]=6;
        int[] i3={7,8};
        int[] i4=new int[8];
        System.arraycopy(i2,0,i4,0,i2.length);
        System.arraycopy(i3,0,i4,6,i3.length);
        System.out.println(Arrays.toString(i4));
        int[] i5=new int[2];
        System.arraycopy(i4,2,i5,0,2);
        System.out.println(Arrays.toString(i5));
    }
}