Java | 배열과 인덱스

Lumpen·2025년 5월 1일
0

Java

목록 보기
34/38

배열

순서가 있고 중복을 허용하는 데이터의 선형 집합

자바에서는 기본 자료형을 제외하고
모두 참조 자료형이므로
배열 또한 참조 자료형이다
배열을 생성하여 변수에 담으면
메모리 어딘가에 배열을 생성하고
변수에서는 생성된 배열의 참조 주소값만을 가지고 있다

인덱스

  • 배열은 인덱스를 사용하여 매우 빠르게 자료를 찾을 수 있다
  • 인덱스를 입력하면 한 번의 연산으로 자료의 위치를 찾을 수 있다

인덱스 사용 예

	int[] arr = new int[2];
    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;

arr 의 주소값이 100 이라고 가정하면
arr[2] 입력으로 arr 의 인덱스 2번 데이터를 참조할 수 있다
이 때 100 + (4byte * 2) 를 하면
108 번에서 4byte 를 차지하고 있는 arr[2] 의 값인 3(int) 에 바로 접근 가능하다

배열의 시작 참조 + (자료의 크기 * 인덱스 위치)

배열의 검색

배열에 들어있는 데이터를 인덱스가 아닌 값으로 찾을 때에는
배열 내의 데이터를 하나씩 비교해야만 한다
따라서 배열의 크기가 클수록 연산 시간이 오래 걸린다

SuppressWarnings

@SuppressWarnings 어노테이션은
개발자가 특정 경고를 인지하고 있다는 것을
알려 경고를 무시하는 것으로
제네릭 타입을 사용하지 않은 코드에서 발생하는 "unchecked" 경고나, 더 이상 사용되지 않는 메서드를 사용했을 때 발생하는 "deprecation" 경고 등을 @SuppressWarnings 어노테이션을 사용하여 숨길 수 있다
경고의 근본적인 원인을 해결하는 것이 아니라 단순히 경고 표시를 억제하는 것으로
해당 경고를 무시해도 안전한 경우에만 신중하게 사용해야 한다

@SuppressWarnings("unchecked")
@SuppressWarnings({"unchecked", ...})
와 같이 사용

배열의 장점

  • 자료 조회 시 O(1)으로 매우 빠르다
  • 메모리 공간이 하나로 이어져 있어 효율적으로 관리할 수 있다

동적 배열

public class ArrayMain {

  public static void main(String[] args) {
    ArrList<String> list = new ArrList<>();
    list.add("a");
    list.add("b");
    list.add("c");

    String a = list.get(0);
    System.out.println(a);
    System.out.println("size: " + list.size());

    list.print();

    System.out.println("----");
    list.pop();
    System.out.println("size: " + list.size());

    list.print();

    System.out.println("----");
    list.add("c");
    list.add("d");
    list.add("e");
    list.remove(1);
    list.print();

  }
}
import java.util.Arrays;

public class ArrList<T> {

  private int size = 0;
  private int length = 0;
  @SuppressWarnings("unchecked")
  private T[] items = (T[]) new Object[0];

  public ArrList() {

  }

  public ArrList(T[] items) {
    this.items = items;
    this.size = items.length;
  }

  public void add(T item) {

    if (size == items.length) {
      size = (int) Math.floor(size * 1.5 + 1);
      items = Arrays.copyOf(items, size);
    }
    items[length] = item;
    length++;
  }

  public void pop() {
    if (size > 0) {
      items[length - 1] = null;
      length--;
    }
  }

  public void remove(int index) {
    if (index < 0 || index >= length) {
      return;
    }
    System.arraycopy(items, index + 1, items, index, length - index - 1);
    items[--length] = null;
  }

  public T get(int index) {
    return items[index];
  }

  public int size() {
    return length;
  }

  public void print() {
    for (int i = 0; i < length; i++) {
      System.out.println(items[i]);
    }
  }

}
profile
떠돌이 생활을 하는. 실업자, 부랑 생활을 하는

0개의 댓글