2024. 1. 20. 20:56ㆍ카테고리 없음
학습하던 중,
자연스럽게 장바구니 예제를 따라치다 보니 자연스럽게 ArrayList 를 사용하게 됐다.
ArrayList 에 대한 지금의 내 지식 수준은
1. 배열의 단점을 보완한 자료구조. 자동적으로 배열 길이가 늘어남.
ㄴ 배열의 단점 : 한 번 생성하면 길이를 바꿀 수 없음.
2. new ArrayList(); 로 생성 시 초기 배열 길이 = 10.
3. 배열 중간에 삭제 등이 발생했을 때, 빈칸을 메우기 위해 값들을 이동시킴.(비용 큰 연산 발생)
정도이다.
배열에 값을 넣는 방법은
배열 길이를 설정하여 생성한 후, 초기화
int[] arr = new int[3];
int[] arr = {값, 값, 값}
초기화 방법_ex
arr = { 1, 2, 3};
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
ArrayList에 값을 넣을 때는
List<E> list = new ArrayList();
list.add(Obejct);
로 간단하게 넣을 수 있는데
솔직히 한 번 쯤은 뜯어 봐야 된다고 생각해서 그냥 하는 중이다.
list.add(Object); 의 리턴 타입은 boolean 이다.
ArrayList 클래스에서 리턴 타입이 boolean 인 add() 를 찾아 보았다.
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
... 영어 넘나 어려운 것.
번역기 돌리면서,
영어도 공부해보고,
뜻도 읽어보면서.. 익혀 보자.
더하다. 지정된 요소. 이 리스트 끝
=> 지정된 요소를 이 리스트 끝에 더하는 메서드이다.
@매개변수 e 는 이 리스트에 더해질 요소이다.
.. (as specified by {@link Collection #add})
컬렉션 프레임 워크에서 지정된 바와 같이 true를 반환한다.
대충 뭔지 알겠다. 이제 add(E e) 를 뜯어보자.
------------------------------------
modCount++; // mod 는 뭐길래 count를 늘릴까;
add(e, elementData, size); // 실제 리스트에 데이터를 추가하는 메서드인 모양.
매개변수 타입으로 미루어 보아
e = list에 추가하려는 요소
elementData = ?
size = 집어넣으려는 요소의 값 크기;
모르는 게 많다. 하나씩 찾아보자.
===============================================
우선 modCount++;
경로를 타고 올라가자 마자 AbstractList 클래스가 열렸다.
AbstractList는 List 인터페이스의 추상 클래스이다.
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
/**
* Sole constructor. (For invocation by subclass constructors, typically
* implicit.)
*/
protected AbstractList() {
}
인터페이스인 List 를 구현함과 동시에, 추상클래스.
알듯 말듯한데, 계속 나아가보자.
근래 학습했던 생성자와 접근제어자가 짬뽕된 protected AbstractList(){} 도 보인다.
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
protected = 같은 패키지 + 다른 패키지지만 상속관계인 곳에서 사용할 수 있음.
=> 추상 클래스인 AbstractList와 상속 관계에 있는 것 = 구현 클래스
=> extends AbstractList<E> 가 선언된 패키지가 다른 서브 클래스에서 사용 가능.
실제로 ArrayList 클래스 파일을 열어보니 상속중이다.
.. 그냥 복습겸 뇌까려봤다.
그래서.. 추상 클래스가 뭔데!
추상 클래스란?
직접적으로 인스턴스화할 수는 없지만, 인터페이스를 구현하는 클래스들이 공통 기능을 제공하도록 도와주는 클래스이다.
/**
* The number of times this list has been <i>structurally modified</i>.
* Structural modifications are those that change the size of the
* list, or otherwise perturb it in such a fashion that iterations in
* progress may yield incorrect results.
*
* <p>This field is used by the iterator and list iterator implementation
* returned by the {@code iterator} and {@code listIterator} methods.
* If the value of this field changes unexpectedly, the iterator (or list
* iterator) will throw a {@code ConcurrentModificationException} in
* response to the {@code next}, {@code remove}, {@code previous},
* {@code set} or {@code add} operations. This provides
* <i>fail-fast</i> behavior, rather than non-deterministic behavior in
* the face of concurrent modification during iteration.
*
* <p><b>Use of this field by subclasses is optional.</b> If a subclass
* wishes to provide fail-fast iterators (and list iterators), then it
* merely has to increment this field in its {@code add(int, E)} and
* {@code remove(int)} methods (and any other methods that it overrides
* that result in structural modifications to the list). A single call to
* {@code add(int, E)} or {@code remove(int)} must add no more than
* one to this field, or the iterators (and list iterators) will throw
* bogus {@code ConcurrentModificationExceptions}. If an implementation
* does not wish to provide fail-fast iterators, this field may be
* ignored.
*/
protected transient int modCount = 0;
다시 본제로 돌아와..
나는 modCount가 뭔지 모른다.
ArrayList 의 public void add(E e){} 에 있던
modCount 는 AbstractList 추상 클래스의 필드라는 것은 확인 했다.
여기서...
또 다시 문제점과 직면한다.
1. 너어어어무 긴 영어 설명문
2. 뉘신지? transient 가 먼지 모름
그냥 기니까 읽기 싫은 거다.. 못 읽는 거 아니다.
할.. 수 있다.
transient 는 따로 경로 타지는 게 없다.
예약어 인듯.
검색 해보자.
.. 이 참에 자바 공식문서도 봐보자.
...

처음엔 이건 줄 알았는데 이상했다.
내가 찾는건 예약어인데 인터페이스가 왜 나오고 설명은 갑자기 우주로 가 버리고..
뒤적뒤적
예약어(keyword)에 관한 공식 설명은 아래 경로에서 얻을 수 있는 것을 확인 했다.
https://docs.oracle.com/javase/specs/
Java SE Specifications
Java Language and Virtual Machine Specifications Java SE 21 Released September 2023 as JSR 396 The Java Language Specification, Java SE 21 Edition HTML | PDF Preview feature: String Templates Preview feature: Unnamed Classes and Instance main methods Previ
docs.oracle.com
아... 재밌다.
찾아가면서 궁금증 풀고 응요할 수 있도록 하는 이 학습 과정이 너무 재밌다.
뭔지도 모르면서 그냥 강제로 때려박힌 지식들.
뭔지 모르니까 실제로 사용하려고 할 때 정말 도움 1도 안 됐었는데
너무 재밌다. 진작에 이랬어야 했는데...
학원 진짜 괜히 갔다.
공식문서에 설명된 내용은 다음과 같다.

변수들은 transient 키워드를 사용해 선언될 수 있다.
그 목적은 transient 키워드가 선언된 변수들은 객체의 영속 상태 중 일부가 아님을 나타내기 위함이다.
위의 예제는 아래의 내용을 설명하고 있다.
클래스 Point 가 시스템 서비스에 의해 영속성 저장소에 저장될 때,
저장되는 멤버변수는 int x 와 y 뿐이다.
이 예시에서는 실제 동작 원리 등을 알 수 없다.
만약 상세 내용이 더욱 궁금하다면 java.io.Serializable 을 참조해라.
해석 해보자.
transient 키워드를 선언한 변수는 영속성 저장소에 저장되지 않는다.
transient 키워드를 통해 해당 변수가 저장 대상이 아님을 나타내기 때문이다.
따라서 protected transient int modCount = 0; 은 실제 사용은 되지만, 저장소 등에는 저장되지 않는 값을 의미한다.
즉.
modCount 는 AbstractList 클래스를 상속한 서브 클래스에서
영속성 저장소에 저장되지 않으면서, 비지니스 로직을 수행하기 위해 필요한 변수이다.
아 후련해.
그래서, modCount 는 어디다 쓰는걸까?
밥 먹고 와서 다시 깊게 파보자.