user2272710
user2272710

Reputation: 1

Making a deep copy using a constructor in Java

I am using these instructions for the method: A constructor, public ProgrammingTeam( ProgrammingTeam p ), that takes a ProgrammingTeam p as a parameter and constructs a deep copy of p. Don’t just write meets = p.meets;. To make a deep copy, you must call ArrayList’s copy constructor: meets = new ArrayList();.

  public ProgrammingTeam( ProgrammingTeam p ) {
    teamName = p.teamName;
    teamMembers = new String [ p.teamMembers.length ];
    for (int i = p.teamMembers.length - 1; i >= 0; i--) {

    }
    meets = new ArrayList < Competition >();
}

I cannot figure out exactly how I am supposed to compose and then finish the deep copy. I know it is going to need a for loop to actually copy every object but I am at a loss, thanks!

Upvotes: 0

Views: 7101

Answers (3)

Bohemian
Bohemian

Reputation: 425168

Regarding the String array...

Strings are immutable, so it is sufficient to simply copy the array, for example using the Arrays.copyOf() utility method:

teamMembers = Arrays.copyOf( p.teamMembers, p.teamMembers.length );

As for the List, it depends...

If Competition is immutable, use ArrayList's copy constructor:

meets = new ArrayList<Competition>(p.meets);

If Competition is mutable, you need to invoke its copy constructor (defining it if required).

meets = new ArrayList<Competition>();
for (Competition c : p.meets) {
    meets.add(new Competition(c));
}

Upvotes: 2

shaunvxc
shaunvxc

Reputation: 182

you need to create a deep copy of all of the ProgrammingTeam parameter p's attributes.

You could do the following:

for(int i = 0; i < p.teamMembers.length -1; i++){
        TeamMember teamMember = new TeamMember();
        // set attributes
        teamMember.setAttribute1(p.teamMembers[i].getAttribute1());
        ...
        teamMember.setAttributeN(p.teamMembers[i].getAttributeN());
         this.teamMembers[i] = teamMember;
 }

Of course, you could simply create a copy constructor for whatever objects are held in the lists that need to be deep copied. The copy constructor would essentially need to accomplish the same sort of thing I described within that for loop.

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

To make a deep copy of String[] teamMembers use java.util.Arrays.copyOf(teamMembers, teamMembers.length)

As for a deep copy of List<Competition> meets you can do it with new ArrayList<Competition>(meets) but it will only be good if Competition is immutable

Upvotes: 0

Related Questions