burak
burak

Reputation: 71

How to copy an array or arraylist

Think there is an array named barca[]. The array have player list. Players are determined as class. For example barca[0]=messi; messi is a player class. I want to copy barca[]. If I write barca2[]=barca[]; I copy the array but when barca2[] changes also barca[] changes. I want them independent. How can I do? ` public class Main {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Player barca[] = new Player[10];
    Player barca2[] = new Player[10];
    for(int i=0; i<10; i++){
        barca[i] = new Player();
        barca[i].id = i;
    }
    barca2 = barca;

    //print the arrays
    for(int i = 0; i<10; i++){
        System.out.print(barca[i].id);
    }
    System.out.println();
    for(int i = 0; i<10; i++){
        System.out.print(barca2[i].id);
    }

    //change an array
    barca2[5].id=100;
    System.out.println();   

    //print the arrays
    for(int i = 0; i<10; i++){
        System.out.print(barca[i].id);
    }
    System.out.println();
    for(int i = 0; i<10; i++){
        System.out.print(barca2[i].id);
    }

}

}

Output:

0123456789 0123456789 012341006789 012341006789 `

Upvotes: 0

Views: 77

Answers (2)

Mahesh Kapoor
Mahesh Kapoor

Reputation: 254

It is simple to implement, if we go by Arraylist then also we get two options as listed, direct and indirect , in sample code. You may edit the object after copying the arraylist. It wouldn't affect the first arraylist. Please check full code for complete understanding.

//1. Direct: Copy player list into player1 List
List<Player> player1 = new ArrayList<Player>(player);

//2. Indirect using method: Copy player list into player1 List
List<Player> player1 = new ArrayList<Player>();
player1.addAll(player);

You may see the complete code here. You may test the code here.

Upvotes: 2

Rustam
Rustam

Reputation: 6515

try this:

List<String>baraca=new ArrayList<>();
        List<String>temp=new ArrayList<>();

        baraca.add("messi 1");
        baraca.add("messi 2");
        baraca.add("messi 3");
        baraca.add("messi 4");
        temp= new ArrayList<String>(baraca);

        temp.add("messi temp");

        System.out.println(baraca);
        System.out.println(temp);

Output:

[messi 1, messi 2, messi 3, messi 4]
[messi 1, messi 2, messi 3, messi 4, messi temp]

Upvotes: 0

Related Questions