简体   繁体   中英

Array of custom Java objects

I am trying to create an array of Person (a class that with variables String name, and double total). But for some reason, creating a second Person replaces(?) the first person. . .

Person[] p = new Person[40];
    
p[0] = new Person("Jango", 32);
p[1] = new Person("Grace", 455);
    
System.out.println( p[0].getName() );
System.out.println( p[1].getName() );
System.out.println( p[0].equals(p[1]) );

The output is:

Grace
Grace
false

Why isn't it:

Jango
Grace
false

????????????

public class Person {

    @SuppressWarnings("unused")
    private Person next;
    private String name;
    private double total;

    public Person(String _name)
    {
        name = _name;
        total = 0.0;
        next = null;
    }

    public Person(String _name, double _total)
    {
        name = _name;
        total = _total;
        next = null;
    }

    public String getName()
    {
        return name;
    }
}

Your problem is that the name instance variable is declared as static, making it a class variable. Any change to name will be changed for every instance of that class.. You need to remove the static identifier from name and from total and your code will work fine.

Currently these variables are static which means that they they will retain the last values assigned.

private static String name;
private static double total;

You need to make these fields class instance variables:

private String name;
private double total;

See Understanding Instance and Class Members

Your fields are static. They should not be, if you want them to be able to store a separate instance of a name and total for each instance of the class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM