[자료구조] 배열(Array)(2): 프로그래밍 언어는 배열을 어떻게 구현했을까? (in Java, Python, C++)

2023. 12. 7. 10:00· Computer Science/Data Structure
목차
  1. 💋 프로그래밍 언어에서의 배열 사용해보기
  2. ✔️ C++
  3. ✔️ Java
  4. ✔️ Python
  5. 💋 자바로 ArrayList 간단하게 구현해보기
  6. 💋 참고자료
반응형
반응형

 

Computer Science 모아보기 👉🏻 https://github.com/seoul-developer/CS

 

GitHub - seoul-developer/CS: 주니어 개발자를 위한 전공 지식 모음.zip

주니어 개발자를 위한 전공 지식 모음.zip. Contribute to seoul-developer/CS development by creating an account on GitHub.

github.com

 

💋 프로그래밍 언어에서의 배열 사용해보기

✔️ C++

 

int a[5] = {1, 2, 3, 4, 5}; //Static Integer Array
int *a = new int[5]; //Dynamic Integer Array

 

✔️ Java

 

import java.util.*;

class GFG {
	public static void main(String[] args)
	{
		// Static Array
		int[] staticArray = new int[5];
		int[] numbers = { 1, 2, 3, 4, 5 };
		// Dynamic Array
		// Create an ArrayList of integers.
		ArrayList<Integer> dynamicArray = new ArrayList<>();

		// Add elements to the dynamic array.
		dynamicArray.add(1);
		dynamicArray.add(2);
		dynamicArray.add(3);

		// Remove an element from the dynamic array.
		dynamicArray.remove(1);
	}
}

 

나는 메인 언어가 자바인 개발자이므로, 자바에서 구현한 동적 배열인 ArrayList에 대해서만 추가적으로 설명을 이어보도록 하겠습니다. 아래에서는 비슷한 느낌으로다가 구현 코드도 넣었으니 참고해주세요.

 

  1. 데이터 추가 (add() )
    • add() 메서드를 사용하여 요소를 배열의 끝에 추가할 수 있다.
    • 메모리 동작: 만약 내부 배열이 가득 차 있으면, 현재 크기의 약 1.5배 정도의 새로운 배열을 할당하고 이전 배열의 요소들을 새 배열로 복사합니다. 그 후 새로운 요소가 추가됩니다.
  2. 데이터 삭제 (remove)
    • remove 메서드를 사용하여 특정 인덱스의 요소를 삭제할 수 있습니다.
    • 메모리 동작: 삭제된 요소 뒤에 있는 모든 요소들을 한 칸씩 앞으로 이동시켜 공간을 메웁니다. 만약 이로 인해 배열의 사용된 크기가 일정 비율 이하로 떨어진다면, shrinkSize() 메서드로 내부 배열의 크기를 줄일 수 있습니다.
  3. 데이터 변경 (set)
    • set 메서드를 사용하여 특정 인덱스의 요소를 변경할 수 있습니다.
    • 메모리 동작: 해당 인덱스의 요소만 변경되며, 배열의 크기나 메모리 할당에는 영향을 미치지 않습니다.
  4. shrinkSize()
    • 사용자가 직접 호출하여 내부 배열의 크기를 현재 요소의 개수에 맞게 조절할 수 있습니다.
    • 메모리 동작: 현재 요소의 개수에 맞게 크기가 조절되며, 불필요한 메모리가 해제됩니다.
  5. Iterator 사용
    • Iterator를 사용하여 배열의 요소를 순회할 수 있습니다.
    • 메모리 동작: 별도의 메모리 할당 없이 배열의 원소에 직접 접근합니다.

 

✔️ Python

 

# Static List
a_static = [1, 2, 3, 4, 5]

# Dynamic List (equivalent to dynamic array in some contexts)
a_dynamic = [0] * 5 # Initialize with zeros, similar to new int[5] in C++

# Alternatively, you can use the list() constructor to create a dynamic list
a_dynamic_alternative = list(range(5))

# Print the lists
print("Static List:", a_static)
print("Dynamic List:", a_dynamic)
print("Dynamic List (alternative):", a_dynamic_alternative)

# Coded By Block_Cipher

 

 

 

💋 자바로 ArrayList 간단하게 구현해보기

 

결과는 아래에!

 

// Java program deals with all operation of a dynamic array
// add, remove, resize memory of array is the main feature
public class DynamicArray {

	// create three variable array[] is a array,
	// count will deal with no of element add by you and
	// size will with size of array[]
	private int array[];
	private int count;
	private int size;
	// constructor initialize value to variable

	public DynamicArray() {
		array = new int[1];
		count = 0;
		size = 1;
	}
	// function add an element at the end of array

	public void add(int data) {

		// check no of element is equal to size of array
		if (count == size) {
			growSize(); // make array size double
		} // insert element at end of array
		array[count] = data;
		count++;
	}

	// function makes size double of array
	public void growSize() {

		int temp[] = null;
		if (count == size) {

			// temp is a double size array of array
			// and store array elements
			temp = new int[size * 2];
			{
				for (int i = 0; i < size; i++) {
					// copy all array value into temp
					temp[i] = array[i];
				}
			}
		}

		// double size array temp initialize
		// into variable array again
		array = temp;

		// and make size is double also of array
		size = size * 2;
	}

	// function shrink size of array
	// which block unnecessary remove them
	public void shrinkSize() {
		int temp[] = null;
		if (count > 0) {

			// temp is a count size array
			// and store array elements
			temp = new int[count];
			for (int i = 0; i < count; i++) {

				// copy all array value into temp
				temp[i] = array[i];
			}

			size = count;

			// count size array temp initialize
			// into variable array again
			array = temp;
		}
	}
	// function add an element at given index

	public void addAt(int index, int data) {
		// if size is not enough make size double
		if (count == size) {
			growSize();
		}

		for (int i = count - 1; i >= index; i--) {

			// shift all element right
			// from given index
			array[i + 1] = array[i];
		}

		// insert data at given index
		array[index] = data;
		count++;
	}

	// function remove last element or put
	// zero at last index
	public void remove() {
		if (count > 0) {
			array[count - 1] = 0;
			count--;
		}
	}

	// function shift all element of right
	// side from given index in left
	public void removeAt(int index) {
		if (count > 0) {
			for (int i = index; i < count - 1; i++) {

				// shift all element of right
				// side from given index in left
				array[i] = array[i + 1];
			}
			array[count - 1] = 0;
			count--;
		}
	}

	public static void main(String[] args) {
		DynamicArray da = new DynamicArray();

		// add 9 elements in array
		da.add(1); // Size of array: 1
		da.add(2); // Size of array: 2
		da.add(3); // Size of array: 4
		da.add(4); // Size of array: 4
		da.add(5); // Size of array: 8
		da.add(6); // Size of array: 8
		da.add(7); // Size of array: 8
		da.add(8); // Size of array: 8
		da.add(9); // Size of array: 16

		// print all array elements after add 9 elements
		System.out.println("Elements of array:");
		for (int i = 0; i < da.size; i++) {
			System.out.print(da.array[i] + " ");
		}

		System.out.println();

		// print size of array and no of element
		System.out.println("Size of array: " + da.size);
		System.out.println("No of elements in array: "
				+ da.count);

		// shrinkSize of array
		da.shrinkSize();

		// print all array elements
		System.out.println("Elements of array after shrinkSize of array:");
		for (int i = 0; i < da.size; i++) {
			System.out.print(da.array[i] + " ");
		}
		System.out.println();

		// print size of array and no of element
		System.out.println("Size of array: " + da.size);
		System.out.println("No of elements in array: "
				+ da.count);

		// add an element at index 1
		da.addAt(1, 22); // Size of array: 18

		// print Elements of array after adding an
		// element at index 1
		System.out.println("Elements of array after add an element at index 1:");
		for (int i = 0; i < da.size; i++) {
			System.out.print(da.array[i] + " ");
		}

		System.out.println();

		// print size of array and no of element
		System.out.println("Size of array: " + da.size);
		System.out.println("No of elements in array: " + da.count);

		// delete last element
		da.remove();

		// print Elements of array after delete last
		// element
		System.out.println("Elements of array after delete last element:");
		for (int i = 0; i < da.size; i++) {
			System.out.print(da.array[i] + " ");
		}

		System.out.println();

		// print size of array and no of element
		System.out.println("Size of array: " + da.size);
		System.out.println("No of elements in array: " + da.count);

		// delete element at index 1
		da.removeAt(1);

		// print Elements of array after delete
		// an element index 1
		System.out.println("Elements of array after delete element at index 1:");
		for (int i = 0; i < da.size; i++) {
			System.out.print(da.array[i] + " ");
		}
		System.out.println();

		// print size of array and no of element
		System.out.println("Size of array: " + da.size);
		System.out.println("No of elements in array: "
				+ da.count);
	}
}

 

 

💋 참고자료

  • https://www.geeksforgeeks.org/how-do-dynamic-arrays-work/

 

도움이 되었다면, 공감/댓글을 달아주면 깃짱에게 큰 힘이 됩니다!🌟
비밀댓글과 메일을 통해 오는 개인적인 질문은 받지 않고 있습니다. 꼭 공개댓글로 남겨주세요!

 

반응형

'Computer Science > Data Structure' 카테고리의 다른 글

[자료구조] 스택(Stack), 큐(Queue): 개념, LinkedList vs ArrayDeque, 시간복잡도 비교  (3) 2023.12.13
[자료구조] ADT(Abstract Data Type)란?: 배열, 스택, 큐, 집합, 맵, 트리, 우선순위 큐의 ADT와 자바에서 구현한 자료구조  (0) 2023.12.09
[자료구조] 자료구조의 개념과 분류: Linear vs Non-Linear, Static vs Dynamic  (0) 2023.12.08
[자료구조] LinkedList: 개념, 종류, ArrayList와의 차이점  (0) 2023.12.07
[자료구조] 배열(Array)(1): 배열의 개념과 메모리 관리, 정적 배열(Array) vs 동적 배열(Dynamic Array)  (0) 2023.12.06
  1. 💋 프로그래밍 언어에서의 배열 사용해보기
  2. ✔️ C++
  3. ✔️ Java
  4. ✔️ Python
  5. 💋 자바로 ArrayList 간단하게 구현해보기
  6. 💋 참고자료
'Computer Science/Data Structure' 카테고리의 다른 글
  • [자료구조] ADT(Abstract Data Type)란?: 배열, 스택, 큐, 집합, 맵, 트리, 우선순위 큐의 ADT와 자바에서 구현한 자료구조
  • [자료구조] 자료구조의 개념과 분류: Linear vs Non-Linear, Static vs Dynamic
  • [자료구조] LinkedList: 개념, 종류, ArrayList와의 차이점
  • [자료구조] 배열(Array)(1): 배열의 개념과 메모리 관리, 정적 배열(Array) vs 동적 배열(Dynamic Array)
깃짱
깃짱
연새데학교 컴퓨터과학과 & 우아한테크코스 5기 백엔드 스타라이토 깃짱
반응형
깃짱
깃짱코딩
깃짱
전체
오늘
어제
  • 분류 전체보기
    • About. 깃짱
    • Weekly Momentum
      • 2024
    • PROJECT
      • AIGOYA LABS
      • Stamp Crush
      • Sunny Braille
    • 우아한테크코스5기
    • 회고+후기
    • Computer Science
      • Operating System
      • Computer Architecture
      • Network
      • Data Structure
      • Database
      • Algorithm
      • Automata
      • Data Privacy
      • Graphics
      • ETC
    • WEB
      • HTTP
      • Application
    • C, C++
    • JAVA
    • Spring
      • JPA
      • MVC
    • AI
    • MySQL
    • PostgreSQL
    • DevOps
      • AWS
      • 대규모 시스템 설계
    • frontend
      • HTML+CSS
    • NextJS
    • TEST
    • Industrial Engineering
    • Soft Skill
    • TIL
      • 2023
      • 2024
    • Linux
    • Git
    • IntelliJ
    • ETC
      • 日本語

블로그 메뉴

  • 홈
  • 깃허브

인기 글

최근 글

태그

  • 예외
  • 우테코5기
  • OOP
  • 람다
  • 우아한테크코스5기
  • 람다와스트림
  • Java
  • Composition
  • 우테코
  • 우아한테크코스
  • TDD
  • lamda
  • 상속과조합
  • 스트림
  • 상속
  • 함수형프로그래밍
  • 컴포지션
  • 조합
  • 레벨로그
  • Stream
hELLO · Designed By 정상우.v4.2.0
깃짱
[자료구조] 배열(Array)(2): 프로그래밍 언어는 배열을 어떻게 구현했을까? (in Java, Python, C++)
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.