python의 기본 배열 구조인 list와 다르게
java의 기본 배열 구조인 Array는 처음 선언할 때 배열의 크기를 지정해주어야 하며 크기는 수정이 불가능하다.
이러한 문제점이 있어 찾던중 Java에도 List 자료구조가 있다는 것을 알게 되었다.
Java의 List도 pyhon의 List와 마찬가지로 삽입과 삭제로 원하는대로 크기를 변경할 수 있다 (물론 처음부터 크기 지정 가능하다)
List<Integer> listA = new ArrayList<>();
List<Integer> listB = new ArrayList<>(100);
List<String> cities = Arrays.asList("Amsterdam", "Paris", "London"); // asList 로 초기화
// new 생성과 동시에 초기화
ArrayList<String> cities = new ArrayList<String>() {{
add("Amsterdam");
add("Paris");
add("London");
}};
List<String> strings = List.of("foo", "bar", "baz"); // List.of 로 초기화
// stream으로 초기화
ArrayList<String> places = new ArrayList<>(Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList()));
List 요소 추가
list.add("값");
list.addFirst(1); //가장 앞에 데이터 추가
list.addLast(2); //가장 뒤에 데이터 추가
list.add(3); //데이터 추가
list.add(1, 10); //index 1 위치에 데이터 10 추가
List 삭제
list.remove("값");
num.removeFirst(); //가장 앞의 데이터 제거
num.removeLast(); //가장 뒤의 데이터 제거
num.remove(); //생략시 0번째 index제거
num.remove(1); //index 1 제거
num.clear(); //모든 값 제거
List 값 변경
list.set(idx, "바꿀값");
List 데이터 출력
list.size();
System.out.println(list.get(0)); // 0번째 index 출력
for(Integer i : list) { // for문을 통한 전체출력
System.out.println(i);
}
List 특정 값 들었는지 확인
list.contains("값");
List 비었는지 확인
list.contains("값");
List에 List 더하기(추가하기? - python에 extend 느낌)
list.addAll(anoterList)
list.addAll(idx, anoterList) -> 특정 인덱스에서 부터 추가
array를 addAll하는 경우
list.addAll(Arrays.asList(배열명));
List 정렬
array는 arrays.sort()로 정렬했었다.
List는 Collections를 사용해서 정렬한다.
Collections.sort(list); // 정렬 (5,7,9)
Collections.sort(list);
Collections.reverse(list); // 정렬 후 역정렬 (9,7,5)
Collections.sort(list, Collections.reverseOrder()); // 역정렬하여 가져오기
java의 set역시 python의 set과 똑같이 중복 값을 삽입할 수 없으며 순서를 갖지 않는다.
Set 선언하기 (LinkedHashSet, TreeSet으로도 가능)
HashSet<데이터타입> set = new HashSet<데이터타입>();
Set에 값 추가하기
set명.add("값");
Set 크기 확인하기
set명.size();
Set 내용 출력할 수 있게 Iterator 안에 담기
Iterator<데이터타입> it = set.Iterator();
Iterator 안에 담은 set 출력하기
Iterator명.next();
or
while(iterator명.hasNext()) {
iterator명.next(); // 값 없을때까지 계속 출력
}