Java에서 어레이를 선언 및 초기화하려면 어떻게 해야 합니까?
Java에서 어레이를 선언 및 초기화하려면 어떻게 해야 합니까?
어레이 선언 또는 어레이 리터럴을 사용할 수 있습니다(단, 변수를 선언하고 바로 영향을 주는 경우에만 어레이 리터럴을 사용하여 어레이를 재할당할 수 없습니다).
기본 유형의 경우:
int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
, 예를 「」입니다.String
똑같아요.
String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
세 번째 초기화 방법은 어레이를 먼저 선언한 후 초기화하거나 어레이를 함수 인수로 전달하거나 어레이를 반환할 때 유용합니다.명시적 유형이 필요합니다.
String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
어레이에는 두 가지 유형이 있습니다.
1차원 어레이
기본값 구문:
int[] num = new int[5];
또는 (선호도가 낮음)
int num[] = new int[5];
값이 지정된 구문(변수/필드 초기화):
int[] num = {1,2,3,4,5};
또는 (선호도가 낮음)
int num[] = {1, 2, 3, 4, 5};
[ : int [ ] num 。여기에는 어레이에 대해 명확하게 설명되어 있습니다.그렇지 않으면 차이가 없다.천만에요.
다차원 배열
선언.
int[][] num = new int[5][2];
또는
int num[][] = new int[5][2];
또는
int[] num[] = new int[5][2];
초기화
num[0][0]=1;
num[0][1]=2;
num[1][0]=1;
num[1][1]=2;
num[2][0]=1;
num[2][1]=2;
num[3][0]=1;
num[3][1]=2;
num[4][0]=1;
num[4][1]=2;
또는
int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };
불규칙한 어레이(또는 비직사각형 어레이)
int[][] num = new int[5][];
num[0] = new int[1];
num[1] = new int[5];
num[2] = new int[2];
num[3] = new int[3];
이치노
른른른:
int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };
액세스의 경우:
for (int i=0; i<(num.length); i++ ) {
for (int j=0;j<num[i].length;j++)
System.out.println(num[i][j]);
}
대체 방법:
for (int[] a : num) {
for (int i : a) {
System.out.println(i);
}
}
너덜너덜한 어레이는 다차원 어레이입니다.
자세한 내용은 공식 Java 튜토리얼에서 다차원 배열 세부 정보를 참조하십시오.
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
또한 유효하지만 변수 유형이 실제로 배열임을 알기 쉽기 때문에 유형 뒤에 괄호를 사용하는 것이 좋습니다.
Java에서 어레이를 선언하는 방법은 다음과 같습니다.
float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};
자세한 내용은 Sun 튜토리얼 사이트와 JavaDoc에서 확인할 수 있습니다.
각 부분을 이해하면 도움이 됩니다.
Type[] name = new Type[5];
Type[]
는 변수 이름('이름'은 ID라고 불립니다)의 유형입니다.리터럴 "Type"은 기본 유형이며, 괄호는 이것이 해당 기본의 어레이 유형임을 나타냅니다.어레이 타입은 독자적인 타입으로 되어 있기 때문에, 다음과 같은 다차원 어레이를 작성할 수 있습니다.Type[][]
( [ ] 라고 입력합니다). " " "new
새로운 어레이에 메모리를 할당하도록 지시되어 있습니다.괄호 사이의 숫자는 새 어레이의 크기와 할당하는 메모리 양을 나타냅니다.를 들어, 타입의 를 하고 있는 .Type
는 32바이트가 소요되며 크기5의 배열을 원하는 경우 32 * 5 = 160바이트를 내부적으로 할당해야 합니다.
또한 다음과 같은 기존 값을 사용하여 어레이를 생성할 수도 있습니다.
int[] name = {1, 2, 3, 4, 5};
빈 공간을 만들 뿐만 아니라 빈 공간을 그 값으로 채웁니다.Java는 기본값이 정수이고 5개라는 것을 알 수 있으므로 어레이의 크기를 암묵적으로 결정할 수 있습니다.
다음은 어레이 선언을 표시하지만 어레이가 초기화되지 않았습니다.
int[] myIntArray = new int[3];
다음은 어레이의 선언과 초기화를 보여 줍니다.
int[] myIntArray = {1,2,3};
다음으로 어레이의 선언과 초기화를 나타냅니다.
int[] myIntArray = new int[]{1,2,3};
그러나 이 세 번째 항목은 참조 변수 "myIntArray"가 가리키는 익명 배열 개체 생성 속성을 보여 줍니다. 따라서 "new int[]{1,2,3};"만 쓰면 익명 배열 개체를 생성할 수 있습니다.
이렇게 적으면:
int[] myIntArray;
이것은 배열 선언은 아니지만 다음 문장으로 위의 선언이 완료됩니다.
myIntArray=new int[3];
또,
// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];
「」라고 하는 합니다.arrayName
(0~9월)
또, 보다 다이나믹한 것을 필요로 하는 경우는, 리스트 인터페이스가 있습니다.이 방법은 동작하지 않지만 유연성이 향상됩니다.
List<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );
배열을 만드는 방법은 크게 두 가지가 있습니다.
이것은 빈 배열의 경우입니다.
int[] array = new int[n]; // "n" being the number of spaces to allocate in the array
그리고 이것은 초기화된 어레이의 경우입니다.
int[] array = {1,2,3,4 ...};
다음과 같이 다차원 배열을 만들 수도 있습니다.
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
int
선언하는 방법에는 여러 가 있습니다.int
스위칭:
int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
모두 ""를 사용할 수 .int i[]
int[] i
.
에서는 '반사를 사용할 수 .(Type[]) Array.newInstance(Type.class, capacity);
에서는 " " " 입니다....
variable arguments
기본적으로 어떤 파라미터라도 상관없습니다.코드로 설명하기가 더 쉽습니다.
public static void varargs(int fixed1, String fixed2, int... varargs) {...}
...
varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
에서는 「」를 참조해 .varargs
으로 int[]
Type...
만 메서드 매개 변수에서메서드파라미터에서만사용할 수 있습니다 사용할 수 있습니다.int... i = new int[] {}
컴파일하지 않을 것이다.컴파일되지 않습니다.
참고로 지나다가 한주의해 주세요.int[]
메서드(또는 다른 어떤 방법(또는 다른 어떤 방법)으로.Type[]
음, 당신.), 세번째 방법 3번째 방법은사용할 수 없습니다를 사용하지 못한다.그 진술 명세서에서int[] i = *{a, b, c, d, etc}*
, 컴파일러는 컴파일러는 다음과 가정합니다같이로 가정한다.{...}
한 의를 의미하 의미하다int[]
왜냐하면 당신은 변수임을 알린다 하지만 그것은.그러나 이는 변수를선언하기 때문입니다.때 메서드에 배열을 신고해야 하거날배열을메서드에 전달할 선언은 때 다음중 하나여야 합니다.new Type[capacity]
★★★★★★★★★★★★★★★★★」new Type[] {...}
.
다차원 어레이
다차원적 배열 훨씬 대처하기가 어렵습니다.다차원 어레이는 다루기가훨씬 어렵습니다.배열의 본질적으로, 2D배열은 배열입니다.기본적으로 2D어레이는 어레이 어레이입니다. int[][]
은 의 배열입니다.int[]
s. 중은, 약 an, 약 an의 ,int[][]
라고 int[x][y]
최대 인덱스는 다음과 같습니다.i[x-1][y-1]
으로 입니다.int[3][5]
말합니다
[0, 0] [1, 0] [2, 0]
[0, 1] [1, 1] [2, 1]
[0, 2] [1, 2] [2, 2]
[0, 3] [1, 3] [2, 3]
[0, 4] [1, 4] [2, 4]
Java 9의 경우
다른 방법 및 방법 사용:
int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();
Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Java 10의 경우
로컬 변수 유형 추론 사용:
var letters = new String[]{"A", "B", "C"};
Java 8에서는 이와 같은 것을 사용할 수 있습니다.
String[] strs = IntStream.range(0, 15) // 15 is the size
.mapToObj(i -> Integer.toString(i))
.toArray(String[]::new);
리플렉션을 사용하여 어레이를 작성하려면 다음과 같이 할 수 있습니다.
int size = 3;
int[] intArray = (int[]) Array.newInstance(int.class, size );
개체 참조 배열 선언:
class Animal {}
class Horse extends Animal {
public static void main(String[] args) {
/*
* Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
*/
Animal[] a1 = new Animal[10];
a1[0] = new Animal();
a1[1] = new Horse();
/*
* Array of Animal can hold Animal and Horse and all subtype of Horse
*/
Animal[] a2 = new Horse[10];
a2[0] = new Animal();
a2[1] = new Horse();
/*
* Array of Horse can hold only Horse and its subtype (if any) and not
allowed supertype of Horse nor other subtype of Animal.
*/
Horse[] h1 = new Horse[10];
h1[0] = new Animal(); // Not allowed
h1[1] = new Horse();
/*
* This can not be declared.
*/
Horse[] h2 = new Animal[10]; // Not allowed
}
}
배열은 일련의 항목 목록입니다.
int item = value;
int [] one_dimensional_array = { value, value, value, .., value };
int [][] two_dimensional_array =
{
{ value, value, value, .. value },
{ value, value, value, .. value },
.. .. .. ..
{ value, value, value, .. value }
};
물체라면 같은 개념입니다.
Object item = new Object();
Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };
Object [][] two_dimensional_array =
{
{ new Object(), new Object(), .. new Object() },
{ new Object(), new Object(), .. new Object() },
.. .. ..
{ new Object(), new Object(), .. new Object() }
};
, 사물의 경우, 사물의 경우 사물의 을 ''에 .null
하기 위해서입니다.new Type(..)
「」등의 .String
★★★★★★★★★★★★★★★★★」Integer
입니다.
String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };
Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };
'을 수 .M
int [][]..[] array =
// ^ M times [] brackets
{{..{
// ^ M times { bracket
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ M times } bracket
;
의할 an an, an an an an an an an an an an an an an an an an를 만드는 것입니다.M
공간 측면에서 차원 배열은 비용이 많이 듭니다.「 」를 M
치수 배열N
모든 치수에서 어레이의 총 사이즈가N^M
각 배열은 참조를 가지며, M차원에는 참조의 (M-1)차원 배열이 있습니다..
Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
// ^ ^ array reference
// ^ actual data
어레이가 '어레이'를 java.util.Arrays
하다, 하다, 하다, 하다.
List<String> number = Arrays.asList("1", "2", "3");
Out: ["1", "2", "3"]
이것은 꽤 간단하고 간단하다.
Java 8 이후를 선언 및 초기화합니다.단순 정수 배열 만들기:
int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[-50, 50]과 [0, 1E17] 사이의 정수에 대해 랜덤 배열 생성:
int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();
2의 거듭제곱:
double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]
String [ ]에는 생성자를 지정해야 합니다.
String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));
다차원 배열:
String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
.toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
하려면 , 「」를 할 수 .java.util.ArrayList
열을정 정의: :
public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
배열에 값 할당:
arrayName.add(new ClassName(class parameters go here);
어레이에서 읽기:
ClassName variableName = arrayName.get(index);
주의:
variableName
를 조작하는 은 배열을 으로, 를 하는 것을 의미합니다.variableName
arrayName
루프의 경우:
//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName
를 편집할 수 arrayName
(이것들)
for (int i = 0; i < arrayName.size(); i++){
//manipulate array here
}
Array List를 선언 및 초기화하기 위한 다른 방법:
private List<String> list = new ArrayList<String>(){{
add("e1");
add("e2");
}};
여기 정답이 많네요.어레이를 작성하기 위한 몇 가지 까다로운 방법을 추가한다(시험의 관점에서 보면 이 점을 이해하는 것이 좋습니다).
어레이 선언 및 정의
int intArray[] = new int[3];
그러면 길이 3의 배열이 생성됩니다.primitive type int를 보유하고 있기 때문에 기본적으로는 모든 값이 0으로 설정됩니다.예를들면,
intArray[2]; // Will return 0
변수 이름 앞에 상자 괄호 [] 사용
int[] intArray = new int[3]; intArray[0] = 1; // Array content is now {1, 0, 0}
어레이 초기화 및 데이터 제공
int[] intArray = new int[]{1, 2, 3};
이번에는 박스 브라켓의 사이즈는 말할 필요도 없습니다.간단한 변형은 다음과 같습니다.
int[] intArray = {1, 2, 3, 4};
길이가 0인 배열
int[] intArray = new int[0]; int length = intArray.length; // Will return length 0
다차원 어레이에서도 유사
int intArray[][] = new int[2][3]; // This will create an array of length 2 and //each element contains another array of length 3. // { {0,0,0},{0,0,0} } int lenght1 = intArray.length; // Will return 2 int length2 = intArray[0].length; // Will return 3
변수 앞에 상자 괄호 사용:
int[][] intArray = new int[2][3];
끝에 박스 브래킷을 하나 붙이면 됩니다.
int[] intArray [] = new int[2][4];
int[] intArray[][] = new int[2][3][4]
몇 가지 예
int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
// All the 3 arrays assignments are valid
// Array looks like {{1,2,3},{4,5,6}}
각 내부 요소의 크기가 같을 필요는 없습니다.
int [][] intArray = new int[2][];
intArray[0] = {1,2,3};
intArray[1] = {4,5};
//array looks like {{1,2,3},{4,5}}
int[][] intArray = new int[][2] ; // This won't compile. Keep this in mind.
위의 구문을 사용하는 경우, 상자 괄호 안에 값을 지정해야 합니다.그렇지 않으면 컴파일되지 않습니다.몇 가지 예:
int [][][] intArray = new int[1][][];
int [][][] intArray = new int[1][2][];
int [][][] intArray = new int[1][2][3];
또 다른 중요한 특징은 공변량이다.
Number[] numArray = {1,2,3,4}; // java.lang.Number
numArray[0] = new Float(1.5f); // java.lang.Float
numArray[1] = new Integer(1); // java.lang.Integer
// You can store a subclass object in an array that is declared
// to be of the type of its superclass.
// Here 'Number' is the superclass for both Float and Integer.
Number num[] = new Float[5]; // This is also valid
중요: 참조되는 유형의 경우 어레이에 저장된 기본값은 null입니다.
배열에는 두 가지 기본 유형이 있습니다.
정적 어레이: 고정 크기 어레이(처음에는 크기를 선언해야 하며 나중에 변경할 수 없습니다)
동적 어레이: 크기 제한은 고려되지 않습니다. (순수한 동적 어레이는 Java에는 없습니다.대신 List가 가장 권장됩니다.)
Integer, string, float 등의 정적 배열을 선언하려면 다음 선언문과 초기화문을 사용합니다.
int[] intArray = new int[10];
String[] intArray = new int[10];
float[] intArray = new int[10];
// Here you have 10 index starting from 0 to 9
동적 기능을 사용하려면 목록...을 사용해야 합니다.리스트는 순수 다이내믹 어레이이므로 처음에 크기를 선언할 필요가 없습니다.Java에서 목록을 선언하는 적절한 방법은 다음과 같습니다.
ArrayList<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");
로컬 변수 유형 추론의 경우 유형을 한 번만 지정하면 됩니다.
var values = new int[] { 1, 2, 3 };
또는
int[] values = { 1, 2, 3 }
배열은 배열 정의에 따라 클래스의 개체뿐만 아니라 원시 데이터 유형을 포함할 수 있습니다.원시 데이터 유형의 경우 실제 값은 인접한 메모리 위치에 저장됩니다.클래스의 객체의 경우 실제 객체는 힙 세그먼트에 저장됩니다.
1차원 어레이:
1차원 배열 선언의 일반적인 형식은 다음과 같습니다.
type var-name[];
OR
type[] var-name;
Java에서의 어레이 인스턴스화
var-name = new type [size];
예를들면,
int intArray[]; // Declaring an array
intArray = new int[20]; // Allocating memory to the array
// The below line is equal to line1 + line2
int[] intArray = new int[20]; // Combining both statements in one
int[] intArray = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Accessing the elements of the specified array
for (int i = 0; i < intArray.length; i++)
System.out.println("Element at index " + i + ": "+ intArray[i]);
참조: Java 어레이
int[] x = new int[enter the size of array here];
예:
int[] x = new int[10];
또는
int[] x = {enter the elements of array here];
예:
int[] x = {10, 65, 40, 5, 48, 31};
선언: 레이이 declare:int[] arr;
:int[] arr = new int[10];
은 어레이 .
배열 선언:int[][] arr;
Array: 다차원 어레이 :int[][] arr = new int[10][17];
10원소, 17은 170원소. 10행 17열 170원소.
배열을 초기화한다는 것은 배열의 크기를 지정하는 것을 의미합니다.
package com.examplehub.basics;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
/*
* numbers[0] = 1
* numbers[1] = 2
* numbers[2] = 3
* numbers[3] = 4
* numbers[4] = 5
*/
System.out.println("numbers[0] = " + numbers[0]);
System.out.println("numbers[1] = " + numbers[1]);
System.out.println("numbers[2] = " + numbers[2]);
System.out.println("numbers[3] = " + numbers[3]);
System.out.println("numbers[4] = " + numbers[4]);
/*
* Array index is out of bounds
*/
//System.out.println(numbers[-1]);
//System.out.println(numbers[5]);
/*
* numbers[0] = 1
* numbers[1] = 2
* numbers[2] = 3
* numbers[3] = 4
* numbers[4] = 5
*/
for (int i = 0; i < 5; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
/*
* Length of numbers = 5
*/
System.out.println("length of numbers = " + numbers.length);
/*
* numbers[0] = 1
* numbers[1] = 2
* numbers[2] = 3
* numbers[3] = 4
* numbers[4] = 5
*/
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
/*
* numbers[4] = 5
* numbers[3] = 4
* numbers[2] = 3
* numbers[1] = 2
* numbers[0] = 1
*/
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
/*
* 12345
*/
for (int number : numbers) {
System.out.print(number);
}
System.out.println();
/*
* [1, 2, 3, 4, 5]
*/
System.out.println(Arrays.toString(numbers));
String[] company = {"Google", "Facebook", "Amazon", "Microsoft"};
/*
* company[0] = Google
* company[1] = Facebook
* company[2] = Amazon
* company[3] = Microsoft
*/
for (int i = 0; i < company.length; i++) {
System.out.println("company[" + i + "] = " + company[i]);
}
/*
* Google
* Facebook
* Amazon
* Microsoft
*/
for (String c : company) {
System.out.println(c);
}
/*
* [Google, Facebook, Amazon, Microsoft]
*/
System.out.println(Arrays.toString(company));
int[][] twoDimensionalNumbers = {
{1, 2, 3},
{4, 5, 6, 7},
{8, 9},
{10, 11, 12, 13, 14, 15}
};
/*
* total rows = 4
*/
System.out.println("total rows = " + twoDimensionalNumbers.length);
/*
* row 0 length = 3
* row 1 length = 4
* row 2 length = 2
* row 3 length = 6
*/
for (int i = 0; i < twoDimensionalNumbers.length; i++) {
System.out.println("row " + i + " length = " + twoDimensionalNumbers[i].length);
}
/*
* row 0 = 1 2 3
* row 1 = 4 5 6 7
* row 2 = 8 9
* row 3 = 10 11 12 13 14 15
*/
for (int i = 0; i < twoDimensionalNumbers.length; i++) {
System.out.print("row " + i + " = ");
for (int j = 0; j < twoDimensionalNumbers[i].length; j++) {
System.out.print(twoDimensionalNumbers[i][j] + " ");
}
System.out.println();
}
/*
* row 0 = [1, 2, 3]
* row 1 = [4, 5, 6, 7]
* row 2 = [8, 9]
* row 3 = [10, 11, 12, 13, 14, 15]
*/
for (int i = 0; i < twoDimensionalNumbers.length; i++) {
System.out.println("row " + i + " = " + Arrays.toString(twoDimensionalNumbers[i]));
}
/*
* 1 2 3
* 4 5 6 7
* 8 9
* 10 11 12 13 14 15
*/
for (int[] ints : twoDimensionalNumbers) {
for (int num : ints) {
System.out.print(num + " ");
}
System.out.println();
}
/*
* [1, 2, 3]
* [4, 5, 6, 7]
* [8, 9]
* [10, 11, 12, 13, 14, 15]
*/
for (int[] ints : twoDimensionalNumbers) {
System.out.println(Arrays.toString(ints));
}
int length = 5;
int[] array = new int[length];
for (int i = 0; i < 5; i++) {
array[i] = i + 1;
}
/*
* [1, 2, 3, 4, 5]
*/
System.out.println(Arrays.toString(array));
}
}
동영상 클래스에 대한 또 다른 완전한 예:
public class A {
public static void main(String[] args) {
class Movie {
String movieName;
String genre;
String movieType;
String year;
String ageRating;
String rating;
public Movie(String [] str)
{
this.movieName = str[0];
this.genre = str[1];
this.movieType = str[2];
this.year = str[3];
this.ageRating = str[4];
this.rating = str[5];
}
}
String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};
Movie mv = new Movie(movieDetailArr);
System.out.println("Movie Name: "+ mv.movieName);
System.out.println("Movie genre: "+ mv.genre);
System.out.println("Movie type: "+ mv.movieType);
System.out.println("Movie year: "+ mv.year);
System.out.println("Movie age : "+ mv.ageRating);
System.out.println("Movie rating: "+ mv.rating);
}
}
String 어레이 초기화에 사용할 수 있습니다.
private static final String[] PROPS = "lastStart,storetime,tstore".split(",");
이를 통해 초기화에 드는 비용을 줄이고 견적 잡음을 줄일 수 있습니다.
어레이를 선언하고 초기화하는 것은 매우 간단합니다.예를 들어 배열에 1, 2, 3, 4, 5개의 정수 요소를 저장하려고 합니다.다음과 같은 방법으로 실행할 수 있습니다.
a)
int[] a = new int[5];
또는
b)
int[] a = {1, 2, 3, 4, 5};
따라서 기본 패턴은 방식 a)에 의한 초기화 및 선언을 위한 것입니다.
datatype[] arrayname = new datatype[requiredarraysize];
datatype
소문자여야 합니다.
따라서 기본 패턴은 방법a에 의한 초기화 및 선언을 위한 것입니다.
문자열 배열인 경우:
String[] a = {"as", "asd", "ssd"};
문자 배열인 경우:
char[] a = {'a', 's', 'w'};
float double의 경우 배열 형식은 정수와 동일합니다.
예를 들어 다음과 같습니다.
double[] a = {1.2, 1.3, 12.3};
단, 어레이를 선언 및 초기화할 때는 수동 또는 루프 등의 방법으로 값을 입력해야 합니다.
단, "method b"로 실행할 경우 값을 수동으로 입력할 필요가 없습니다.
언급URL : https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java
'source' 카테고리의 다른 글
Vue 앱으로 p5 가져오기 (0) | 2022.07.26 |
---|---|
Element UI 테이블 행의 링크를 올바르게 설정하는 방법(간단해야 합니까?) (0) | 2022.07.26 |
Java에서 두 개의 필드를 기준으로 정렬하려면 어떻게 해야 합니까? (0) | 2022.07.26 |
html select 태그에서 vue.js 값을 얻는 방법 (0) | 2022.07.26 |
콤마 구분 배열 출력 방법 (0) | 2022.07.26 |