데이터 구조: 배열
정적 배열
배열은 모든 요소가 순차적으로 배열되는 선형 데이터 구조입니다. 이는 연속 메모리 위치에 저장된 동일
데이터 유형의 요소 모음입니다.초기화
public class Array<T> { private T[] self; private int size; @SuppressWarnings("unchecked") public Array(int size) { if (size <= 0) { throw new IllegalArgumentException("Invalid array size (must be positive): " + size); } else { this.size = size; this.self = (T[]) new Object[size]; } } }
Core Array Class에서는 배열의 크기와 배열 초기화를 위한 일반적인 뼈대를 저장할 예정입니다. 생성자에서는 배열의 크기를 요청하고 객체를 만들고 이를 원하는 배열에 캐스팅하는 형식을 취합니다.
설정 방법
public void set(T item, int index) { if (index >= this.size || index < 0) { throw new IndexOutOfBoundsException("Index Out of bounds: " + index); } else { this.self[index] = item; } }
이 메소드는 항목을 저장할 배열과 인덱스에 저장할 항목을 요청하는 메소드입니다.
메소드 가져오기
public T get(int index) { if (index >= this.size || index < 0) { throw new IndexOutOfBoundsException("Index Out of bounds"); } else { return self[index]; } }
Get 메소드는 인덱스를 요청하고 해당 인덱스에서 항목을 검색합니다.
인쇄 방법
public void print() { for (int i = 0; i < size; i++) { System.out.println(this.self[i]+" "); } }
인쇄 방법은 각 항목 사이에 공백을 두고 한 줄로 배열의 모든 구성원을 인쇄하는 것입니다.
정렬된 배열
배열이지만 요소 자체를 정렬하는 기능이 있습니다.
초기화
public class SortedArray<T extends Comparable<T>> { private T[] array; private int size; private final int maxSize; @SuppressWarnings("unchecked") public SortedArray(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("Invalid array max size (must be positive): " + maxSize); } this.array = (T[]) new Comparable[maxSize]; this.size = 0; this.maxSize = maxSize; } }
Sorted Array Class에서는 배열의 크기를 저장하고 배열의 최대 크기와 배열 초기화를 위한 일반 뼈대도 요청합니다. 생성자에서는 배열의 최대 크기를 요청하고 객체를 만들고 이를 원하는 배열에 캐스팅하는 유형을 지정합니다.
게터
public int length() { return this.size; } public int maxLength() { return this.maxSize; } public T get(int index) { if (index < 0 || index >= this.size) { throw new IndexOutOfBoundsException("Index out of bounds: " + index); } return this.array[index]; }
삽입 방법
private int findInsertionPosition(T item) { int left = 0; int right = size - 1; while (left <= right) { int mid = (left + right) / 2; int cmp = item.compareTo(this.array[mid]); if (cmp < 0) { right = mid - 1; } else { left = mid + 1; } } return left; } public void insert(T item) { if (this.size >= this.maxSize) { throw new IllegalStateException("The array is already full"); } int position = findInsertionPosition(item); for (int i = size; i > position; i--) { this.array[i] = this.array[i - 1]; } this.array[position] = item; size++; }
Insert 메소드는 정렬된 형태로 해당 위치에 항목을 삽입합니다.
삭제방법
public void delete(T item) { int index = binarySearch(item); if (index == -1) { throw new IllegalArgumentException("Unable to delete element " + item + ": the entry is not in the array"); } for (int i = index; i < size - 1; i++) { this.array[i] = this.array[i + 1]; } this.array[size - 1] = null; size--; }
검색 방법
private int binarySearch(T target) { int left = 0; int right = size - 1; while (left <= right) { int mid = (left + right) / 2; int cmp = target.compareTo(this.array[mid]); if (cmp == 0) { return mid; } else if (cmp < 0) { right = mid - 1; } else { left = mid + 1; } } return -1; } public Integer find(T target) { int index = binarySearch(target); return index == -1 ? null : index; }
트래버스 방법
public void traverse(Callback<T> callback) { for (int i = 0; i < this.size; i++) { callback.call(this.array[i]); } }
콜백 인터페이스
public interface Callback<T> { void call(T item); }
순회에서 콜백 인터페이스 사용
public class UppercaseCallback implements UnsortedArray.Callback<String> { @Override public void call(String item) { System.out.println(item.toUpperCase()); } }
정렬되지 않은 배열
위에서도 거의 똑같습니다
초기화와 게터는 동일합니다.
삽입 방법
public void insert(T item) { if (this.size >= this.maxSize) { throw new IllegalStateException("The array is already full"); } else { this.self[this.size] = item; this.size++; } }
삭제방법도 동일
검색방법
public Integer find(T target) { for (int i = 0; i < this.size; i++) { if (this.self[i].equals(target)) { return i; } } return null; }
동적 배열
동적 배열은 배열 목록 또는 목록과 같습니다.
초기화
public class DynamicArray<T> { private T[] array; private int size; private int capacity; @SuppressWarnings("unchecked") public DynamicArray(int initialCapacity) { if (initialCapacity <= 0) { throw new IllegalArgumentException("Invalid initial capacity: " + initialCapacity); } this.capacity = initialCapacity; this.array = (T[]) new Object[initialCapacity]; this.size = 0; } }
삽입 방법
private void resize(int newCapacity) { @SuppressWarnings("unchecked") T[] newArray = (T[]) new Object[newCapacity]; for (int i = 0; i < size; i++) { newArray[i] = array[i]; } array = newArray; capacity = newCapacity; } public void insert(T item) { if (size >= capacity) { resize(2 * capacity); } array[size++] = item; }
삭제 방법
public void delete(T item) { int index = find(item); if (index == -1) { throw new IllegalArgumentException("Item not found: " + item); } for (int i = index; i < size - 1; i++) { array[i] = array[i + 1]; } array[--size] = null; if (capacity > 1 && size <= capacity / 4) { resize(capacity / 2); } }
다른 건 다 똑같습니다.
이것이 배열 작업에 도움이 되기를 바랍니다. 행운을 빌어요!
위 내용은 데이터 구조: 배열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

일부 애플리케이션이 제대로 작동하지 않는 회사의 보안 소프트웨어에 대한 문제 해결 및 솔루션. 많은 회사들이 내부 네트워크 보안을 보장하기 위해 보안 소프트웨어를 배포 할 것입니다. ...

많은 응용 프로그램 시나리오에서 정렬을 구현하기 위해 이름으로 이름을 변환하는 솔루션, 사용자는 그룹으로, 특히 하나로 분류해야 할 수도 있습니다.

시스템 도킹의 필드 매핑 처리 시스템 도킹을 수행 할 때 어려운 문제가 발생합니다. 시스템의 인터페이스 필드를 효과적으로 매핑하는 방법 ...

데이터베이스 작업에 MyBatis-Plus 또는 기타 ORM 프레임 워크를 사용하는 경우 엔티티 클래스의 속성 이름을 기반으로 쿼리 조건을 구성해야합니다. 매번 수동으로 ...

IntellijideAultimate 버전을 사용하여 봄을 시작하십시오 ...

Java 객체 및 배열의 변환 : 캐스트 유형 변환의 위험과 올바른 방법에 대한 심층적 인 논의 많은 Java 초보자가 객체를 배열로 변환 할 것입니다 ...

전자 상거래 플랫폼에서 SKU 및 SPU 테이블의 디자인에 대한 자세한 설명이 기사는 전자 상거래 플랫폼에서 SKU 및 SPU의 데이터베이스 설계 문제, 특히 사용자 정의 판매를 처리하는 방법에 대해 논의 할 것입니다 ...

Redis 캐싱 솔루션은 제품 순위 목록의 요구 사항을 어떻게 인식합니까? 개발 과정에서 우리는 종종 a ... 표시와 같은 순위의 요구 사항을 처리해야합니다.
