J. Ike
J. Ike

Reputation: 19

Can't access correct class object outside of class

I have a class containing that I've declared static volatile because I want to have different classes access the same instance of it. When the class is instantiated I thought it would create one instance of my hashmap but apparently it has created 2 instances.

Class 1:

public class FlightMap {

private Flight flight;
private static volatile HashMap<String, Flight> flight_hm;

public FlightMap() {
    flight = new Flight();
    HashMap<String, Flight> flight_hm = new HashMap<>();
}

public int GetSize() {
    int size = flight_hm.size();
    return size;
}

Class 2 // Calling Class

public class GetFlightThread extends Thread {

@Override
public void run() {

    String ref;
    FlightMap fm = new FlightMap();
    int size=0;

    size = fm.GetSize();
}

When I look in the debugger inside Class 1, there are 2 instances of "flight_hm", one has size of zero and is static, and the other is null and non-static. The "size" variable in Class 2 is null, so apparently Class 2 is accessing the non-static instance. How can I create only 1 instance of "fm"?

Upvotes: 0

Views: 108

Answers (2)

Ariel Grabijas
Ariel Grabijas

Reputation: 1512

Local variable flight_hm declared in class constructor and your static variable flight_hm are two different variables. So what basically happened here is that you declared static variable, but you didn't initialized it, and you also declared and initialized local variable in constructor. Consider using this keyword as a good practice in the future, to avoid those kind of mistakes.

public class FlightMap {

    private Flight flight;
    private static volatile HashMap<String, Flight> flight_hm = new HashMap<>();

    public FlightMap() {
        flight = new Flight();
    }

    public int GetSize() {
        int size = this.flight_hm.size();
        return size;
    }
}

Upvotes: 0

Joe C
Joe C

Reputation: 15684

HashMap<String, Flight> flight_hm = new HashMap<>();

↑ This is declaring a local variable and assigning to that local variable. This local variable is masking the static variable you have at the class level.

When you declare a static variable, you will want to initialize it on the same line as it is declared, like so:

private static volatile HashMap<String, Flight> flight_hm = new HashMap<>();

Upvotes: 2

Related Questions