第五章:数组与集合

  1. 性能方面优先考虑数组:
    对基本类型进行求和运算时,数组的效率是集合的10倍。

  2. 对数组扩容方法:
    public class expandCapacity {
        public static void main(String[] args) {
            String arrays[] = new String[10];
            System.out.println(arrays.length);
            arrays = expandCapacity(arrays,13);
            System.out.println(arrays.length);
        }
        public static  <T> T[] expandCapacity(T[] datas,int newlen){
            newlen = newlen < 0 ? 0 : newlen;
            return Arrays.copyOf(datas,newlen);
        }
    }
  3. 警惕数组的浅拷贝:
    public class shallowCopy {
        public static void main(String[] args) {
            int balloonNum=7;
            Balloon[] box = new Balloon[balloonNum];
            for (int i=0;i<balloonNum;i++){
                box[i]=new Balloon(Color.values()[i],i);
            }
            Balloon[] copybox = Arrays.copyOf(box,box.length);
            copybox[6].setColor(Color.blue);
           //打印:
            for (Balloon ballon:box){
                System.out.print(ballon.getColor()+"id:"+ballon.getId()+"  ");
            }
            System.out.println();
            System.out.println("copybox数组的值:");
            for (Balloon ballon:copybox){
                System.out.print(ballon.getColor()+"id:"+ballon.getId()+"  ");
            }
        }
        public static class Balloon{
            Color color;
            int id;
            @Override
            public String toString() {
                return "Balloon{" +
                        "color='" + color + '\'' +
                        ", id=" + id +
                        '}';
            }
            public Balloon(Color color, int id) {
                this.color = color;
                this.id = id;
            }
            public Color getColor() {
                return color;
            }
            public void setColor(Color color) {
                this.color = color;
            }
            public int getId() {
                return id;
            }
            public void setId(int id) {
                this.id = id;
            }
        }
        public static enum Color{
            Red,Orange,yellow,green,indigo,blue,violet;
        }
    }

    输出的值是:

猜你喜欢

转载自www.cnblogs.com/yaohuiqin/p/9340973.html