allocating for array and then using constructor

2020-04-10 06:33发布

Person.java

public class Person {
    public String firstName, lastName;

    public Person(String firstName,
            String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFullName() {
        return(firstName + " " + lastName);
    }
}

PersonTest.java

public class PersonTest {
    public static void main(String[] args) {
        Person[] people = new Person[20];              //this line .
        for(int i=0; i<people.length; i++) {
            people[i] = 
                new Person(NameUtils.randomFirstName(),
                        NameUtils.randomLastName());  //this line
        }
        for(Person person: people) {
            System.out.println("Person's full name: " +
                    person.getFullName());
        }
    }
}

In above code, we used twice "new". Is this code is correct or wrong? First one is for allocation of array. But why the second one? It's from lecture notes.

3条回答
forever°为你锁心
2楼-- · 2020-04-10 07:04

new Person[20] creates an array that can hold 20 references to Person objects. It does not create any actual Person objects.

new Person(...) creates a Person object.

The critical distinction to make here is that unlike in C or C++, new Person[20] does not allocate memory for 20 Person objects. The array does not contain the actual objects; it only contains references to them.

查看更多
够拽才男人
3楼-- · 2020-04-10 07:06

Yes, it is correct.

The line:

Person[] people = new Person[20]

allocates the array, full of references to null while the line:

new Person(NameUtils.randomFirstName(),
                      NameUtils.randomLastName());  //this line

fills it [the array] by instantiating objects of type Person, and assigning the reference in the array.

查看更多
老娘就宠你
4楼-- · 2020-04-10 07:10
Person[] people = new Person[20];

only allocates memory for objects Person (filled with nulls). Then you need to fill it with particular Persons (with random name and surname int this example).

查看更多
登录 后发表回答