简体   繁体   中英

Different Object Array Elements Refer to the Same Object?

I have an object array that I am using to store different objects. When I try to get the data from either object, it gives the last object's data. I made some new testing files and cut everything down to the problem itself. Here is what I mean:

public class Test
{
  public static ObjectTest[] objArray = new ObjectTest[2];

  public static void main(String[] args)
  {
    objArray[0] = new ObjectTest("Jimmy");
    objArray[1] = new ObjectTest("Terry");
    System.out.println(objArray[0].getName());
    System.out.println(objArray[1].getName());
  }
}

This outputs:

Terry
Terry

Here is ObjectTest.java as well:

public class ObjectTest
{
  private static String name;

  public ObjectTest(String nm)
  {
    name = nm;
  }

  public static String getName()
  {
    return name;
  }
}

What's making this print out the name for the last object? Aren't there supposed to be 2 different objects here? There seems to be only 1.

Static variables shared between all the class instances, the last value overrides everything you set before. Use instance variables instead of static:

public class Main {
    public static ObjectTest[] objArray = new ObjectTest[2];

    public static void main(String[] args) {
        objArray[0] = new ObjectTest("Jimmy");
        objArray[1] = new ObjectTest("Terry");
        System.out.println(objArray[0].getName());
        System.out.println(objArray[1].getName());
    }
}

class ObjectTest {
    private String name;

    public ObjectTest(String nm) {
        name = nm;
    }

    public String getName() {
        return name;
    }
}

Output:

Jimmy
Terry

name is a static field here, it is just one for every instance of class ObjectTest . Delete static keywords everywhere.

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