Programming

Java로 객체 배열 만들기

procodes 2020. 5. 20. 22:13
반응형

Java로 객체 배열 만들기


나는 Java를 처음 사용했고 당분간 Java로 객체 배열을 만들었습니다.

예를 들어 클래스 A가 있습니다.

A[] arr = new A[4];

그러나 이것은 4 개의 객체가 아닌 A에 대한 포인터 (참조) 만 생성합니다. 이 올바른지? 생성 된 객체의 함수 / 변수에 액세스하려고하면 null 포인터 예외가 발생합니다. 내가 해야하는 객체를 조작하거나 액세스하려면

A[] arr = new A[4];
for( int i=0; i<4; i++ )
    arr[i] = new A();

이것이 맞습니까? 아니면 내가 잘못하고 있습니까? 이것이 맞다면 정말 이상합니다.

편집 : C ++에서 새로운 A [4]라고 말하고 4 개의 객체를 생성하기 때문에이 이상한 것을 발견했습니다.


맞습니다.

A[] a = new A[4];

이 작업을 수행하는 것과 유사한 4 A 참조를 만듭니다.

A a1;
A a2;
A a3;
A a4;

이제 a1을 할당하지 않고 a1.someMethod ()를 수행 할 수 없었습니다.

a1 = new A();

마찬가지로 배열을 사용하여 수행해야합니다

a[0] = new A();

사용하기 전에.


맞습니다. 당신은 또한 할 수 있습니다 :

A[] a = new A[] { new A("args"), new A("other args"), .. };

이 구문은 메소드 인수와 같이 어디서나 배열을 작성하고 초기화하는 데 사용될 수 있습니다.

someMethod( new A[] { new A("args"), new A("other args"), . . } )

예, 참조 만 작성하며 기본값은 null로 설정됩니다. 그렇기 때문에 NullPointerException이 발생합니다. 개체를 별도로 만들고 참조를 할당해야합니다. Java로 배열을 만드는 3 단계가 있습니다-

선언 –이 단계에서는 만들려는 배열의 데이터 유형과 차원을 지정합니다. 그러나 크기의 크기는 아직 언급하지 않았습니다. 그들은 비어 있습니다.

인스턴스화 –이 단계에서는 새 키워드를 사용하여 배열을 만들거나 배열에 메모리를 할당합니다. 이 단계에서는 배열 차원의 크기를 언급합니다.

초기화 – 배열은 항상 데이터 유형의 기본값으로 초기화됩니다. 그러나 우리는 우리 자신의 초기화를 할 수 있습니다.

자바에서 배열 선언

이것이 Java로 1 차원 배열을 선언하는 방법입니다.

int[] array;
int array[];

Oracle은 배열을 선언 할 때 이전 구문을 사용하는 것이 좋습니다. 법적 선언의 다른 예는 다음과 같습니다.

// One Dimensional Arrays
int[] intArray;             // Good
double[] doubleArray;

// One Dimensional Arrays
byte byteArray[];           // Ugly!
long longArray[];

// Two Dimensional Arrays
int[][] int2DArray;         // Good
double[][] double2DArray;

// Two Dimensional Arrays
byte[] byte2DArray[];       // Ugly
long[] long2DArray[];

그리고 이것은 불법 선언의 몇 가지 예입니다.

int[5] intArray;       // Don't mention size!
double{} doubleArray;  // Square Brackets please!

인스턴스화

이것이 우리가 어레이를“인스턴트 화”하거나 메모리를 할당하는 방법입니다

int[] array = new int[5];

JVM이 new키워드를 발견하면 무언가를 위해 메모리를 할당해야한다는 것을 이해합니다. 그리고을 지정 int[5]하면 int크기 5 s 배열이 필요하다는 것을 의미합니다 . 따라서 JVM은 메모리를 작성하고 새로 할당 된 메모리의 참조를 배열에 "할당"유형으로 지정합니다.int[]

초기화

Using a Loop – Using a for loop to initialize elements of an array is the most common way to get the array going. There’s no need to run a for loop if you are going to assign the default value itself, because JVM does it for you.

All in One..! – We can Declare, Instantiate and Initialize our array in one go. Here’s the syntax –

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

Here, we don’t mention the size, because JVM can see that we are giving 5 values.

So, until we instantiate the references remain null. I hope my answer has helped you..! :)

Source - Arrays in Java


Here is the clear example of creating array of 10 employee objects, with a constructor that takes parameter:

public class MainClass
{  
    public static void main(String args[])
    {
        System.out.println("Hello, World!");
        //step1 : first create array of 10 elements that holds object addresses.
        Emp[] employees = new Emp[10];
        //step2 : now create objects in a loop.
        for(int i=0; i<employees.length; i++){
            employees[i] = new Emp(i+1);//this will call constructor.
        }
    }
}

class Emp{
    int eno;
    public Emp(int no){
        eno = no;
        System.out.println("emp constructor called..eno is.."+eno);
    }
}

You are correct. Aside from that if we want to create array of specific size filled with elements provided by some "factory", since Java 8 (which introduces stream API) we can use this one-liner:

A[] a = Stream.generate(() -> new A()).limit(4).toArray(A[]::new);
  • Stream.generate(() -> new A()) is like factory for separate A elements created in a way described by lambda, () -> new A() which is implementation of Supplier<A> - it describe how each new A instances should be created.
  • limit(4) sets amount of elements which stream will generate
  • toArray(A[]::new) (can also be rewritten as toArray(size -> new A[size])) - it lets us decide/describe type of array which should be returned.

For some primitive types you can use DoubleStream, IntStream, LongStream which additionally provide generators like range rangeClosed and few others.


Yes it is correct in Java there are several steps to make an array of objects:

  1. Declaring and then Instantiating (Create memory to store '4' objects):

    A[ ] arr = new A[4];
    
  2. Initializing the Objects (In this case you can Initialize 4 objects of class A)

    arr[0] = new A();
    arr[1] = new A();
    arr[2] = new A();
    arr[3] = new A();
    

    or

    for( int i=0; i<4; i++ )
      arr[i] = new A();
    

Now you can start calling existing methods from the objects you just made etc.

For example:

  int x = arr[1].getNumber();

or

  arr[1].setNumber(x);

For generic class it is necessary to create a wrapper class. For Example:

Set<String>[] sets = new HashSet<>[10]

results in: "Cannot create a generic array"

Use instead:

        class SetOfS{public Set<String> set = new HashSet<>();}
        SetOfS[] sets = new SetOfS[10];  

The genaral form to declare a new array in java is as follows:

type arrayName[] = new type[numberOfElements];

Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).

Lets initialize an array to store the salaries of all employees in a small company of 5 people:

int salaries[] = new int[5];

The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.

Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:

int salaries[] = {50000, 75340, 110500, 98270, 39400};

Or to do it at a later point like this:

salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;

More visual example of array creation: enter image description here

To learn more about Arrays, check out the guide.

참고URL : https://stackoverflow.com/questions/5364278/creating-an-array-of-objects-in-java

반응형