우선 한 가지 문제를 해결해 볼까요? Listing 1 은 두 ArrayList 데이터 내에서 공통 원소만을 뽑아 모으는 프로시저, either 를 자바 언어를 이용해 만든 것입니다. 만일 두 ArrayList 내의 모든 원소를 합쳐 모으는 프로시저, both 가 필요하다면 어떻게 하면 좋을까요?
Listing1. FirstQuizSet
import java.util.*;
public class FirstQuizSet {
public static ArrayList both(ArrayList xs, ArrayList ys) {
// TODO: 이 곳을 채우는 문제입니다.
}
public static ArrayList either(ArrayList xs, ArrayList ys) {
ArrayList eitherList = new ArrayList();
Object y = null; Iterator elems = ys.iterator();
while (elems.hasNext()) {
y = elems.next();
if (xs.contains(y)) eitherList.add(y);
}
return eitherList;
}
public static ArrayList toArrayList(int[] xs) {
ArrayList ys = new ArrayList();
for (int i = 0; i < xs.length; i++) ys.add(new Integer(xs[i]));
return ys;
}
public static void main(String[] args) {
int[] xVec = { 1, 3, 4, 5, 6, 9, 7 };
int[] yVec = { 4, 5, 8, 9, 10, 15, -1 };
ArrayList xs = toArrayList(xVec); ArrayList ys = toArrayList(yVec);
System.out.println( both(xs, ys) ); System.out.println( either(xs, ys) );
}
}
Listing 1 의 실행 결과 예시
[1, 3, 4, 5, 6, 9, 7, 8, 10, 15, -1] ß both 의 실행 결과
[4, 5, 9] ß either 의 실행 결과
댓글을 달아 주세요
댓글 RSS 주소 : http://dbilove.com/tt/foleafs/rss/comment/165