java中数组复制的四种方式

package com.Test.Demo.Test;

import java.util.Arrays;

public class CopyTest {
    public static void main(String[] args){
        //实现数组复制的四种方法:
        Book[] b1 ={new Book("asd",12),new Book("qwe",90)};//原数组
        Book[] b2 =b1.clone();//Object中的对象克隆方法 需要注意的是被克隆的类需要实现Cloneable接口并且覆写clone方法
        Book[] b3=new Book[3];
        System.arraycopy(b1,0,b3,1,1);//利用了系统提供的拷贝方式
        Book[] b4= Arrays.copyOf(b1,2);//利用Arrays中的copyOf方法
        Book[] b5= Arrays.copyOfRange(b1,1,2);//利用Arrays中的copyOfRange方法 注意参数的含义
       for(int i=0;i<b2.length;i++){
           System.out.println(b2[i]);
       }
       for(int i=0;i<b3.length;i++){
           System.out.println(b3[i]);
       }
       for(int i=0;i<b4.length;i++){
           System.out.println(b4[i]);
       }
       for(int i=0;i<b5.length;i++){
           System.out.println(b5[i]);
       }
    }

}
class Book implements Cloneable{
    private String name;
    private int title;
    public Book(){

    }
    public Book(String name, int title) {
        this.name = name;
        this.title = title;
    }

    public String getName() {
        return name;
    }

    public int getTitle() {
        return title;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setTitle(int title) {
        this.title = title;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", title=" + title +
                '}';
    }
}
posted @ 2020-05-29 13:45  键盘_书生  阅读(40)  评论(0编辑  收藏  举报