>  기사  >  Java  >  Java의 3D 배열

Java의 3D 배열

WBOY
WBOY원래의
2024-08-30 15:27:261204검색

Java의 3D 배열을 이해하기 전에 배열이 무엇인지, 프로그래밍 언어에서는 왜 사용되는지 알아야 합니다. 배열은 기본적으로 동일한 이름으로 참조되는 유사한 유형의 값 그룹입니다. 유사한 유형이란 동일한 데이터 유형의 값을 의미합니다. 학급의 모든 학생 이름을 저장하려는 상황을 생각해 보세요. Student의 이름은 String 데이터 유형이므로 각 학생의 이름을 다른 변수에 저장하는 것은 많은 공간을 차지할 뿐만 아니라 거의 동일한 이름을 증가시켜 프로그램에서도 혼란을 야기하므로 올바르지 않습니다. 코드 줄. 따라서 이러한 유형의 상황을 처리하기 위해 배열이 사용됩니다. 프로그래머는 Student_names 배열을 만들고 배열 개체 생성 시 크기를 지정할 수 있습니다. 이렇게 하면 각 학생 이름에 변수 이름을 지정할 필요가 없으며 값을 업데이트하고 삽입하고 검색할 때마다 이 배열의 인덱스를 사용할 수 있습니다.

Java에서 배열 변수는 다른 변수와 유사하게 데이터 유형 뒤에 [] 기호를 붙여 선언합니다. 배열 크기는 배열 생성 시 정의되어야 하며 일정하게 유지됩니다. 배열 요소는 숫자 인덱스로 액세스되며 첫 번째 요소는 0 인덱스에 저장됩니다. Java에는 기본적으로 1차원 배열과 다차원 배열이라는 두 가지 유형의 배열이 있습니다. 3D 배열은 다차원 배열 범주에 속합니다. 다차원 배열은 간단히 말해서 배열의 배열로 정의할 수 있고, 3차원 배열은 2차원 배열의 배열입니다. 3D는 다차원 배열의 복잡한 형태입니다. 건물 내 아파트 시나리오를 생각해 보세요. 아파트가 10층이고 각 층에 5개의 아파트가 있으며 각 아파트에는 3개의 방이 있다고 가정합니다. 프로그래밍에서 이 데이터를 처리하기 위해 3D 배열이 사용됩니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

Java에서 3D 배열은 어떻게 정의되나요?

Java는 매우 간단한 방법을 사용하여 배열을 정의합니다. 배열의 데이터 유형 다음에 배열 객체를 정의하는 데 대괄호('[ ]')가 사용됩니다. 배열을 선언할 때 크기를 정의해야 합니다. 3D 배열은 세 개의 대괄호로 정의됩니다. 아래에는 Java에서 3D 배열을 정의하는 구문이 나와 있습니다.

Data_type array_name[ ] [ ] [ ] = new array_name[a][b][c];
  • 여기서 data_type: 배열에 저장될 요소의 데이터 유형입니다. array_name: 배열 이름
  • new: Java에서 객체를 생성하는 키워드
  • a, b, c: 다양한 차원에 대한 숫자 값을 보유합니다.

구문:

int [ ] [ ] [ ] arr = new int [10][4][3];

위 예시에서 'arr' 배열에 저장되는 요소 수는 최대 10x4x3 = 120개입니다.

Java에서 3D 배열을 만들고 값을 삽입하는 방법은 무엇입니까?

Java에서 3D 배열을 만드는 것은 1D 및 2D 배열을 만드는 것만큼 간단합니다. 위에서 언급했듯이 배열 선언 시 배열의 크기를 정의하는 것이 중요합니다. 3D 배열을 생성하려면 2D 배열의 배열 형태로 값을 전달/입력하는 단계가 하나 더 필요합니다. 배열의 크기를 정의하고 나중에 값을 삽입/입력하거나 배열의 값을 직접 전달할 수 있습니다. 따라서 3D 배열에 정의된 값의 방식은 다음과 같습니다.

구문

data_type[][][] arr_name =
{
{
{Array1Row1Col1,Array1Row1Col2,....},
{Array1Row2Col1, Array1Row2Col2, ....}
},
{
{Array2Row1Col1, Array2Row1Col2, ....},
{Array2Row2Col1, Array2Row2Col2, ....}
}
}

코드

int num_array [ ] [ ] [ ] = {
{
{10 ,20 ,99},
{30 ,40 ,88}
},
{
{50 ,60 ,77},
{80 ,70 ,66}
},
};

배열은 배열 안에 있으므로 2차원 배열의 배열이라고 합니다. 위의 예에서 명확하게 보면 숫자의 2D 배열이 두 개 있고 이것은 2D입니다.

Java에서 3D 배열 요소를 초기화하는 방법은 무엇입니까?

위에서 언급한 것처럼 전체 배열을 한 번에 초기화하는 것은 3D 배열로 작업할 때 향후 프로그래밍 시 혼란을 줄일 수 있는 모범 사례입니다. 아래에 언급된 방식으로 배열에 한 번에 하나의 값을 할당할 수도 있습니다.

구문:

int employee_arr[ ] [ ] [ ] = new int [10][3][3];
employee_arr[0][0][0] = 100; // it will assign value 100 at very first element of employee_arr employee_arr[0][0][1] = 200; // it will assign value 200 at second element of employee_arr employee_arr[0][0][2] = 300; // it will assign value 100 at third element of employee_arr

위의 접근 방식은 공간을 많이 차지하고 코드 줄이 늘어나기 때문에 번거롭고 좋은 접근 방식으로 간주되지 않습니다. 루프를 사용하는 한 가지 접근 방식도 있는데, 이는 3D 배열 작업 시 좋은 방법으로 간주됩니다.

구문:

int Student_arr [ ] [ ] [ ] = new arr [2] [3] [4]; int x, y, z, value;
for(x = 0; x< 2; x++) {
for(y = 0; y< 3; y++) {
for(z = 0; z< 4; z++) {
Student_arr[x][y][z] = value; value= value*2;
}
}
}

위의 예에서 모든 배열 요소는 x = no인 루프를 사용하여 삽입됩니다. 테이블 수, y= 총 행 수, z는 Student_arr라는 3D 배열의 총 열 수를 나타냅니다.

Java에서 3D 배열 요소에 액세스하는 방법은 무엇입니까?

Java에서는 아래에 제공된 것과 유사한 인덱스로 초기화했기 때문에 인덱스를 사용하여 배열의 단일 요소에 액세스할 수 있습니다.

구문:

int arr [ ] [ ] [ ] = new arr [3] [3] [3];
// Accessing the array elements of 3D arrays in Java using indices

구문:

System.out.println("The first element of array is" + arr[0][0][0]);

In the above syntax, it will retrieve the element at [0][0][0] index of the array ‘arr’, but normally if we want to retrieve all the elements of an array, then this approach is not followed, and elements are accessed through loops as it retrieves all elements at once. While accessing elements through loops, 3 loops are used in which the first loop defines the total number of tables and the second loop defines the rows, and the third loop defines the columns as given below:

Code:

class Student{
public static void main(String[] args) {
// student_arr is the name of 3d array int[][][] student_arr= {
{
{10, 20, 30},
{20, 30, 40}
},
{
{40, 50, 60},
{10, 70, 80},
}
};
// for loop to iterate through each element of 3D array for (tables = 0; tables<2; tables++)
{
for (rows= 0; rows <2; rows++)
{
for (columns= 0; columns<3; columns++)
{
System.out.print("student_arr[" +tables+ "][" +rows+ "][" +columns+ "] = "
+student_arr[tables][rows][columns]+ "\t");
}
System.out.println();
}
System.out.println();
}
}

Output:

student_arr[0] [0] [0] = 10 student_arr[0] [0] [1] = 20 student_arr[0] [0] [2] = 30
student_arr[0] [1] [0] = 20 student_arr[0] [1] [1] = 30 student_arr[0] [1] [2] = 40
student_arr[1] [0] [0] = 40 student_arr[1] [0] [1] = 50 student_arr[1] [0] [2] = 60
student_arr[1] [1] [0] = 10 student_arr[1] [1] [1] = 70 student_arr[1] [1] [2] = 80

How to Remove Elements of 3D Arrays in Java?

  • Removing elements in 3D arrays in Java is simple and similar to the one initializing them. Array class does not provide any direct method to add or delete an element from the arrays. As the size of the array cannot be increased or decreased dynamically so simple programming logic is applied to perform this task. Simply we can use 3 loops to traverse the whole array by specifying the index at which we want to remove the element. We can create a new array or copy the original array leaving the element which needs to be removed.
  • Through this process of removing and updating elements in the 3D array is rarely used. Instead, ArrayList is used in these types of cases as it provides various functions to directly remove elements from it. In ArrayList ‘remove()’ method, remove elements at the provided index in an ArrayList. If we have repeating values in an array and we want to remove the first occurrence in the Array, we can use, ArrayUtils.removeElement(array, element) method for the same, which takes 2 arguments, i.e. the whole array and the element which needs to be removed from it.

How to Update Elements

There is as such no method to update elements in a 3D array. Some programming logic is applied to modify the elements, like removing the elements by traverse the whole array with the use of 3 loops and perform the modification either at the particular index or in the whole array. For such a complex task, this processing is not preferred through 3D arrays and done through the use of the collection, ArrayList. In ArrayList set(int index, E element) is used to modify or update the element dynamically in an array. It takes 2 arguments, i.e. the index and element with the modified and updated value.

Conclusion

As we mentioned above, how to work on 3D arrays in Java. Working with multidimensional arrays in Java is somewhat difficult for the new programmers as it involves various loops, but understanding it through the stepwise procedure and keeping in mind the basic rules while working with arrays can make it much easier to work on it.

위 내용은 Java의 3D 배열의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Java의 2D ArrayList다음 기사:Java의 2D ArrayList