Reputation: 464
I have 2 ArrayList that I need to swap out the elements between the two from a certain starting point.
My current code looks something like this:
List<Character> seq1 = new ArrayList<Character>(someArrayList);
List<Character> seq2 = new ArrayList<Character>(someArrayList);
List<Character> tmp1 = new ArrayList<Character>(someArrayList);
List<Character> tmp2 = new ArrayList<Character>(someArrayList);
for(int i = start1; i <= seq1.size()-1; i++){
tmp1.set(i,seq2.get(i));
}
for(int i = start2; i <= seq2.size()-1; i++){
tmp2.set(i,seq1.get(i));
}
for(int i = start1; i <= seq1.size()-1; i++){
tmp1.set(i,seq2.get(i));
}
for(int i = start2; i <= seq2.size()-1; i++){
tmp2.set(i,seq1.get(i));
}
Assuming start1
, and start2
are both 4
For instance:
seq1: {A,A,A,A,B,B,B,B}
seq2: {A,A,A,A,C,C,C,C}
The end result should be:
seq1:{A,A,A,A,C,C,C,C}
seq2:{A,A,A,A,B,B,B,B}
But mine still seem to be returning with their original values. Any help is greatly appreciated.
Upvotes: 2
Views: 187
Reputation: 8652
In the case of collection you will not need any temporary swapping variable or other thing. Just replace the values.
for(int i = start1, j = start2; i < seq1.size() && j < seq2.size(); i++, j++){
seq1.set(i, seq2.set(j, seq1.get(i)));
}
Upvotes: 1
Reputation: 22974
List<Character> seq1 = new ArrayList<Character>();
List<Character> seq2 = new ArrayList<Character>();
seq1.add('A');
seq1.add('B');
seq1.add('B');
seq2.add('A');
seq2.add('C');
seq2.add('C');
List<Character> tmp1 = new ArrayList<Character>(seq1);
List<Character> tmp2 = new ArrayList<Character>(seq2);
int start1 = 1, start2 = 1;
for(int i = start1; i <= seq1.size()-1; i++){
tmp1.set(i,seq2.get(i));
}
for(int i = start2; i <= seq2.size()-1; i++){
tmp2.set(i,seq1.get(i));
}
System.out.println(tmp1.toString());
}
It works.
The problem is you are modifying list tmp1 and tmp2
. So content gets modified in temp lists.
And It seems you are trying to print original list which was not modified by your code
Upvotes: 0