Please show a detailed solution Thank you Consider the follo
Please show a detailed solution. Thank you!
Consider the following class: public class MergeSequence public class MergeSequence {private ArrayList values; public MergeSequence () {values = new ArrayList();} public void add(int n) {values.add(n);} public String toString() {return values.toString();}} Add a method public MergeSequence append (MergeSequence other) that creates a new sequence, appending this and the other sequence, without modifying either sequence. For example, if sequence is: 14 9 16 and b is the sequence 9 7 4 9 11 then the call a.append(b) returns the sequence 1 4 9 16 9 7 4 9 11 without modifying a or b. Use JUnit testing framework to verify the functionality of your MergeSequence Class.Solution
Hi, Please find my implementation.
Please let me know in case of any issue.
import java.util.ArrayList;
public class MergeSequence {
private ArrayList<Integer> values;
public MergeSequence(){
values = new ArrayList<>();
}
public void add(int n){
values.add(n);
}
public String toString(){
return values.toString();
}
//1
public MergeSequence append(MergeSequence other){
MergeSequence result = new MergeSequence();
// adding current object values
for(Integer x : this.values){
result.add(x);
}
// adding other values
for(Integer x : other.values){
result.add(x);
}
// returning result
return result;
}
public static void main(String[] args) {
// creating MergeSequence Object and adding some int value in it
MergeSequence mg1 = new MergeSequence();
mg1.add(1);
mg1.add(4);
mg1.add(9);
mg1.add(16);
// creating other MergeSequence Object and adding some int value in it
MergeSequence mg2 = new MergeSequence();
mg2.add(9);
mg2.add(7);
mg2.add(4);
mg2.add(9);
mg2.add(11);
// getting final MergeSequence Object
MergeSequence result = mg1.append(mg2);
System.out.println(result.toString());
}
}
/*
Sample run:
[1, 4, 9, 16, 9, 7, 4, 9, 11]
*/

