Java의 배열: 특성, 사용법 및 실제 시나리오
이 기사에서는 고정 크기, 효율적인 액세스, 유형 안전성 등 Java 배열의 특성을 탐색하면서 이를 ArrayList와 같은 동적 컬렉션 유형과 비교합니다. 또한 제품 수량 저장, 일일 기온 수정, 학생 성적 정렬 등의 실제 시나리오를 제공하여 Java에서 배열의 실제 적용을 보여줍니다.
Java에서 배열은 개발자가 동일한 유형의 여러 값을 단일 변수에 저장할 수 있는 기본 데이터 구조입니다. 어레이는 고정된 크기와 직접 액세스 기능으로 인해 데이터를 관리하고 조작하는 효율적인 방법을 제공합니다. 이 기사에서는 Java 배열의 특성을 살펴보고 이를 ArrayList와 같은 다른 컬렉션 유형과 비교하며 배열이 유용한 실제 시나리오를 제시합니다. 효율적인 Java 프로그램을 구축하려면 배열의 속성과 응용 프로그램을 이해하는 것이 필수적입니다.
아래는 Java의 배열 특성 목록입니다.
- 고정 크기: 일단 정의되면 배열의 크기를 변경할 수 없습니다.
- 순서 지정: 배열은 요소를 순차적 순서로 저장합니다. 즉, 요소는 일정한 시간에 인덱스를 통해 액세스할 수 있습니다.
- 효율성: 배열의 모든 요소에 액세스하는 것은 일정한 시간 작업입니다. 어레이는 단일 유형의 데이터를 저장하기 때문에 메모리 오버헤드가 매우 낮습니다.
- 단일 유형: Java 배열은 유형이 지정됩니다. 즉, 배열 선언에 선언된 것과 동일한 데이터 유형의 요소만 저장할 수 있습니다.
배열은 목록이자 컬렉션 인터페이스의 일부인 ArrayList와 다릅니다. Java의 인터페이스는 클래스와 유사한 참조 유형으로, 상수, 기본 메소드, 정적 메소드 및 중첩 유형만 포함할 수 있습니다(Tutorials Point, n. d.). 컬렉션 인터페이스의 경우 add(), 제거(), get(), size() 등의 메소드가 포함됩니다(Oracle Doc., n.d.). 이를 통해 ArrayList, LinkedList 및 Set 클래스와 같은 다양한 유형의 목록 클래스에서 해당 메소드를 사용할 수 있습니다.
배열은 컬렉션 인터페이스의 일부가 아닙니다. 즉, 연관된 메소드가 없습니다.
배열 사용의 실제 시나리오
시나리오 1 매장 내 매장 제품 수량:
배열을 사용하여 매장에 있는 다양한 제품의 수량을 추적할 수 있습니다. 예를 들어 배열의 각 요소는 특정 제품의 수량을 나타냅니다.
public class Main { public static void main(String[] args) { // Stores product quantities int[] quantities = new int[4]; // Storing product quantities quantities[0] = 50; quantities[1] = 30; quantities[2] = 20; quantities[3] = 40; // Prints the product quantities for (int i = 0; i < quantities.length; i++) { System.out.println("Product " + (i + 1) + " Quantity: " + quantities[i]); } } }
출력:
Product 1 Quantity: 50 Product 2 Quantity: 30 Product 3 Quantity: 20 Product 4 Quantity: 40
시나리오-2:
배열을 사용하여 일일 온도를 저장하고 수정할 수 있습니다.
public class Main { public static void main(String[] args) { // Stores daily temperatures int[] temperatures = {68, 70, 75, 72, 69, 71, 73}; // Prints initial temperatures System.out.println("Initial daily temperatures:"); printTemperatures(temperatures); // Modifies temperatures modifyTemperature(temperatures, 2, 78); modifyTemperature(temperatures, 5, 74); // Prints updated temperatures System.out.println("\nUpdated daily temperatures:"); printTemperatures(temperatures); } // Method to print all temperatures public static void printTemperatures(int[] temperatures) { String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday", "Sunday"}; for (int i = 0; i < temperatures.length; i++) { System.out.println(days[i] + ": " + temperatures[i] + "°F"); } } // Method to modify a temperature public static void modifyTemperature(int[] temperatures, int dayIndex, int newTemperature) { if (dayIndex >= 0 && dayIndex < temperatures.length) { temperatures[dayIndex] = newTemperature; } else { System.out.println("Invalid day index!"); } } }
출력:
public class Main { public static void main(String[] args) { // Stores product quantities int[] quantities = new int[4]; // Storing product quantities quantities[0] = 50; quantities[1] = 30; quantities[2] = 20; quantities[3] = 40; // Prints the product quantities for (int i = 0; i < quantities.length; i++) { System.out.println("Product " + (i + 1) + " Quantity: " + quantities[i]); } } }
시나리오-3:
배열을 사용하여 특정 수업에서 학생들의 성적을 저장하고 정렬할 수 있습니다.
Product 1 Quantity: 50 Product 2 Quantity: 30 Product 3 Quantity: 20 Product 4 Quantity: 40
출력
public class Main { public static void main(String[] args) { // Stores daily temperatures int[] temperatures = {68, 70, 75, 72, 69, 71, 73}; // Prints initial temperatures System.out.println("Initial daily temperatures:"); printTemperatures(temperatures); // Modifies temperatures modifyTemperature(temperatures, 2, 78); modifyTemperature(temperatures, 5, 74); // Prints updated temperatures System.out.println("\nUpdated daily temperatures:"); printTemperatures(temperatures); } // Method to print all temperatures public static void printTemperatures(int[] temperatures) { String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday", "Sunday"}; for (int i = 0; i < temperatures.length; i++) { System.out.println(days[i] + ": " + temperatures[i] + "°F"); } } // Method to modify a temperature public static void modifyTemperature(int[] temperatures, int dayIndex, int newTemperature) { if (dayIndex >= 0 && dayIndex < temperatures.length) { temperatures[dayIndex] = newTemperature; } else { System.out.println("Invalid day index!"); } } }
요약하자면 Java 배열은 크기가 고정되어 있으며 동일한 유형의 여러 값을 저장합니다. 인덱스를 사용하여 요소에 대한 효율적이고 지속적인 액세스를 제공하므로 메모리 오버헤드와 속도가 문제가 되는 시나리오에 적합합니다. 배열은 ArrayList와 같은 컬렉션의 유연성을 제공하지 않지만 여전히 정렬된 데이터를 효율적으로 처리하기 위한 Java 툴킷의 귀중한 부분입니다.
참고자료:
오라클 문서. (n.d.). 컬렉션(Java SE 21) [Java 플랫폼, Standard Edition Java API 사양]. 신탁. https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Collection.html/에서 검색
튜토리얼 포인트. (n.d.). 자바 인터페이스. 튜토리얼 포인트. https://www.tutorialspoint.com/java/java_interfaces.htm에서 검색
원본은 2024년 10월 16일 Level UP Coding에서 발행한 Medium의 Alex.omegapy에 게시되었습니다.
위 내용은 Java의 배열: 특성, 사용법 및 실제 시나리오의 상세 내용입니다. 자세한 내용은 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 ... 표시와 같은 순위의 요구 사항을 처리해야합니다.
