Allocating for an array and then using a constructor

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 full name: " +
                    person.getFullName());
        }
    }
}

      

In the above code, we have used "new" twice. Is this code correct or incorrect? The first is to select an array. But why the second? This is from lectures.

+3


source to share


3 answers


Yes, that's right.

Line:

Person[] people = new Person[20]

      



allocates an array full of references to null

, while the line:

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

      

populates it [array] by creating objects of type Person

and assigning a reference to the array.

+10




new Person[20]

creates an array that can contain 20 object references Person

. It doesn't create any real objects Person

.

new Person(...)

creates an object Person

.



The critical difference here is that unlike C or C ++, it new Person[20]

does not allocate memory for 20 Person

objects. The array contains no real objects; it only contains links to them.

+10


source


Person[] people = new Person[20];

      

allocates memory only for Person objects (padded with zeros). Then you need to fill it with specific Persons (with a random first and last name in this example).

+2


source







All Articles