Copy constructor and defensive copy

Copy constructor and defensive copy

Medium Java OOP Basics 17 views
Explanation Complexity

Problem Statement

Task: create a class Team holding int[] scores. Use defensive copy in constructor.

Input Format

An integer n
Then n integers (scores)

Output Format

Stored scores inside Team object

Example

3
10 20 30
[10, 20, 30]

Constraints

• n ≥ 0

• Must use defensive copy in constructor

Concept Explanation

If we directly assign the array reference,
outside changes will affect internal data.

Defensive copy means:
Create a new array and copy elements inside constructor.

Step-by-Step Explanation

1.Create class Team.

2.Declare private int[] scores;

3.In constructor:

• Create new array of same length.

• Copy elements manually.

4.Provide getter that also returns copy (optional but safer).

Concept Explanation

If we directly assign the array reference,
outside changes will affect internal data.

Defensive copy means:
Create a new array and copy elements inside constructor.

Step-by-Step Explanation

1.Create class Team.

2.Declare private int[] scores;

3.In constructor:

• Create new array of same length.

• Copy elements manually.

4.Provide getter that also returns copy (optional but safer).

Input / Output Format

Input Format
An integer n
Then n integers (scores)
Output Format
Stored scores inside Team object
Constraints
• n ≥ 0

• Must use defensive copy in constructor

Examples

Input:
3 10 20 30
Output:
[10, 20, 30]

Example Solution (Public)

Java
static class Team{private final int[] scores;Team(int[] s){scores=new int[s.length];for(int i=0;i<s.length;i++) scores[i]=s[i];}int getScore(int i){return scores[i];}}

Official Solution Code

static class Team{private final int[] scores;Team(int[] s){scores=new int[s.length];for(int i=0;i<s.length;i++) scores[i]=s[i];}int getScore(int i){return scores[i];}}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.