자바에서 배열을 선언하고 초기화하려면 어떻게해야합니까?

StackOverflow https://stackoverflow.com/questions/1200621

  •  05-07-2019
  •  | 
  •  

문제

자바에서 배열을 선언하고 초기화하려면 어떻게해야합니까?

도움이 되었습니까?

해결책

배열 선언 또는 배열 리터럴을 사용할 수 있지만 (변수를 즉시 선언하고 영향을 미치는 경우에만 배열 리터럴을 배열 재 할당하는 데 사용할 수 없습니다).

원시 유형의 경우 :

int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};

예를 들어 수업의 경우 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"};

더 많은 정보를 찾을 수 있습니다 선 튜토리얼 사이트와 Javadoc.

다음은 배열의 선언을 보여 주지만 배열은 초기화되지 않았습니다.

 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];

각 부분을 이해하면 도움이된다고 생각합니다.

Type[] name = new Type[5];

Type[] 입니다 유형변하기 쉬운 이름 ( "이름"은 이름이라고합니다 식별자). 문자 그대로의 "유형"은 기본 유형이며, 브래킷은 이것이 해당베이스의 배열 유형임을 의미합니다. 배열 유형은 차례로 자체 유형이므로 다차원 배열을 만들 수 있습니다. Type[][] (유형의 배열 유형 []). 키워드 new 새 배열에 대한 메모리를 할당하라고 말합니다. 브래킷 사이의 숫자는 새 배열의 크고 할당 할 메모리의 양을 말합니다. 예를 들어, Java가 기본 유형을 알고 있다면 Type 32 바이트를 가져 가면 크기 5의 배열을 원합니다. 내부적으로 32 * 5 = 160 바이트를 할당해야합니다.

다음과 같은 값으로 배열을 만들 수도 있습니다.

int[] name = {1, 2, 3, 4, 5};

빈 공간을 생성 할뿐만 아니라 해당 값으로 채 웁니다. Java는 프리미티브가 정수이고 그 중 5 개가 있다고 말할 수 있으므로 배열의 크기는 암시 적으로 결정될 수 있습니다.

대안 적으로,

// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];

호출 된 배열이 선언됩니다 arrayName 크기 10 (사용할 요소 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[]), 당신은 세 번째 방법을 사용할 수 없습니다. 성명서에서 int[] i = *{a, b, c, d, etc}*, 컴파일러는 {...} 의미를 의미합니다 int[]. 그러나 그것은 당신이 변수를 선언하기 때문입니다. 배열을 메소드로 전달할 때는 선언이 new Type[capacity] 또는 new Type[] {...}.

다차원 배열

다차원 배열은 다루기가 훨씬 어렵습니다. 기본적으로 2D 배열은 배열 배열입니다. int[][] 배열을 의미합니다 int[]에스. 열쇠는 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]

반사를 사용하여 배열을 만들려면 다음과 같이 할 수 있습니다.

 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
    }
}

Java 9

다른 사용 IntStream.iterate 그리고 IntStream.takeWhile 행동 양식:

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"};

배열은 순차적 인 항목 목록입니다

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
;

그것을 만드는 것은 주목할 가치가 있습니다 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.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
}

Java 8에서는 이렇게 사용할 수 있습니다.

String[] strs = IntStream.range(0, 15)  // 15 is the size
    .mapToObj(i -> Integer.toString(i))
    .toArray(String[]::new);

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();

두 가지 전원 시퀀스 :

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.Arrays:

List<String> number = Arrays.asList("1", "2", "3");

Out: ["1", "2", "3"]

이것은 예쁘다 단순한 그리고 간단합니다. 다른 답변에서 보지 못했기 때문에 추가 할 수 있다고 생각했습니다.

배열 목록을 선언하고 초기화하는 또 다른 방법 :

private List<String> list = new ArrayList<String>(){{
    add("e1");
    add("e2");
}};

로컬 변수 유형 추론을 사용하면 유형을 한 번만 지정하면됩니다.

var values = new int[] { 1, 2, 3 };

또는

int[] values = { 1, 2, 3 }

여기에 많은 답변. 어레이를 만들기 위해 몇 가지 까다로운 방법을 추가합니다 ( 시험 이것을 아는 것이 좋습니다)

  1. 배열을 선언하고 정의하십시오

    int intArray[] = new int[3];
    

이렇게하면 길이 3의 배열이 생성됩니다. 원시 유형 int가 기본적으로 0으로 설정된 모든 값이 유지됩니다.

    intArray[2]; // will return 0
  1. 변수 이름 앞에 상자 브래킷을 사용합니다

    int[] intArray = new int[3];
    intArray[0] = 1;  // array content now {1,0,0}
    
  2. 배열에 데이터를 초기화하고 제공합니다

    int[] intArray = new int[]{1,2,3};
    

    이번에는 박스 브래킷의 크기를 언급 할 필요가 없습니다. 이것의 간단한 변형조차도

    int[] intArray = {1,2,3,4};
    
  3. 길이 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

IMP : 참조 된 유형의 경우 배열에 저장된 기본값은 NULL입니다.

배열 선언 : int[] arr;

배열 초기화 : int[] arr = new int[10]; 10은 배열에서 허용되는 요소 수를 나타냅니다.

다차원 배열 선언 : int[][] arr;

다차원 배열 초기화 : int[][] arr = new int[10][17]; 10 행 17은 170이기 때문에 10 행과 17 개의 열과 170 개의 요소입니다.

배열을 초기화한다는 것은 크기를 지정하는 것을 의미합니다.

int[] SingleDimensionalArray = new int[2]

int[][] MultiDimensionalArray = new int[3][4]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top