Subject : ArrayList안에 ArrayList 넣는 방법.
Import
import java.util.ArrayList;
문제
피타고라스 정리를 이용해서 각변의 길이의 합이 20이하이면서
각변의 길이가 정수인 모든 직각삼각형의 모든 변을 구하여라.
나의 풀이
import java.util.ArrayList;
public class Book {
public static void main(String[] args) {
ArrayList<ArrayList<Integer>> answerList = new ArrayList<ArrayList<Integer>>();
for (int a= 1; a <= 20; a++) {
for (int b= 1; b <= 20; b++) {
for (int c= 1; c <= 20; c++) {
if ((a*a+b*b == c*c)&&(a+b+c <= 20)){
ArrayList<Integer> tempList = new ArrayList<Integer>();
tempList.add(a);
tempList.add(b);
tempList.add(c);
answerList.add(tempList);
}
}
}
}
System.out.println(answerList);
}
}
결과
[[3, 4, 5], [4, 3, 5]]
해석
»→. ArrayList를 선언해줄때 기본적으로
ArrayList listName = new ArrayList();
이런식으로 선언해주지만,
ArrayList<Integer> listName = new ArrayList<Integer>();
ArrayList<String> listName = new ArrayList<String>();
이와 같이 미리 안에 들어갈 타입을 정해 줄 수 있다.
이 경우 다른 타입을 리스트 안에 넣으려고 하면 에러가 난다.
»→. 비슷한 원리로
ArrayList<ArrayList<Integer>> answerList = new
를 선언하게 되면 Integer가 들어있는 ArrayList만 answerList에 추가 할 수 있다.
»→. 이 원리로 추가할 요소가 있을때
ArrayList<Integer> tempList = new ArrayList<Integer>();
tempList.add(a);
tempList.add(b);
tempList.add(c);
이 처럼 ArrayList를 만들고
answerList.add(tempList);
이와 같이 answerList 에 추가해주면 된다.
배경
해당문제를 푸는건 어렵지 않았으나, 리스트 안에 리스트를 넣는 방법을 몰랐다. Python에서는
answerList = []
answerList.append([a,b,c])
이런식으로 했을텐데 타입을 먼저 선언해줘야하는 JAVA에서는 어떻게 해야하는지 몰랐다
주요 참고 페이지
'JAVA > [JAVA]' 카테고리의 다른 글
기본형 매개변수와 참조형 매개변수 (0) | 2022.10.23 |
---|---|
JVM의 메모리 구조 (1) | 2022.10.23 |
배열.clone() (0) | 2022.10.17 |
equals()와 == 의 차이점 (0) | 2022.10.17 |
replace 와 replaceAll (String에서 숫자만 제거하기) (2) | 2022.10.15 |