이 프로그램은 소스 목록을 쌍으로 섞습니다. 그래서 그 원래 목록
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13 ","14 ","15 ","16 ","17 ","18 ","19 ","20 "
trasfoms to
11 ^ 12 19 ^ 20 17 ^ 18 15 ^ 16 1 ^ 2 5 ^ 6 3 ^ 4 13 ^ 14 7 ^ 8 9 ^ 10
위의 내용은 주석 처리 된 줄이 주석 처리되지 않은 상태입니다. 이제 A 행 이 주석 처리 되면 shuffleList의 모든 요소는 19^20
입니다.
public class ShuffleService {
public static void shuffleList(List<String> list) {
System.out.println(list);
ArrayList<String[]> shuffleList = new ArrayList<String[]>(10);
String[] arr = new String[2];
boolean flag = false;
int step = 0;
for(String s: list){
if(flag){
arr[1]=s;
} else {
arr[0]=s;
}
flag=!flag;
step++;
if(step==2){
shuffleList.add(arr);
step=0;
//arr = new String[2]; //**line A**
}
}
Collections.shuffle(shuffleList);
for(String[] val: shuffleList){
System.out.print(val[0]);
System.out.print("^");
System.out.println(val[1]);
}
}
public static void main(String[] args) {
String[] a = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20"};
List<String> list1 = Arrays.asList(a);
shuffleList(list1);
}
}
그렇다면 제대로 작동하려면 프로그램에서 A 행의 주석을 제거해야하는 이유는 무엇입니까?
값을 다시 작성 arr
하지 않고 다시 쓸 때 이미 목록에있는 값도 수정해야하기 때문입니다.
목록에 개체를 추가한다고해서 수정이 중단되는 것은 아니며 자체적으로 복사본을 만들지 않습니다. new String[2]
루프를 호출 하면 목록에 추가하는 각 쌍에 대해 새 문자열 배열을 효과적으로 구축 할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다