user2631901
user2631901

Reputation: 1

Java public hashtables

So I want to be able to have a public hashtable (kind of like how you would have a public String or int etc etc field). How would I go about doing that? I've tried something like this:

public class Home {
    public static Hashtable<String, Double> test = new Hashtable<String, Double>();

    public static void main(String[] args) {
        test.put("A", 1.2);
        test.put("B", 1.3);
        test.put("C", 1.4);

        System.out.println(test.get("A");
    }
}       

I would like to be able to access the Hashtable and its information in another class though. What would be the method to go about doing that? Is what I have sufficient? Thanks.

Upvotes: 0

Views: 498

Answers (4)

Paul Vargas
Paul Vargas

Reputation: 42010

If several threads access to the variable, may you want to use:

public static final Map<String, Double> test = new ConcurrentHashMap<>();

You can access from another class with

double value = Home.test.get("A");

Upvotes: 0

arynaq
arynaq

Reputation: 6870

The map can be reached with Home.test as in Home.test.put("A", 1.2) but you should use encapsulation. Note that the static keyword means all instances of the class share the same map, if you want it to be unique per instance you must remove the static keyword.

Declare the Map (it is better to use the interface) as private and provide getter/setter.

public class ClassWithTheTable{

    private static Map<String, Double> table = new Hashtable<String,Double)>();

    public Map<String, Double> getTable(){
      return table;
    }

    public void setTable(Map<String,Double> table){
      this.table = table;
    }
    //Rest of code ommited.
}

Upvotes: 0

Zhe
Zhe

Reputation: 396

You should be able to access the Map as Home.test

However, you won't have added any of the initial values. You'll need a separate method to do that.

Upvotes: 0

peter.murray.rust
peter.murray.rust

Reputation: 38033

public static void main(String[] args) {
        Home.test.put("A", 1.2);
        Home.test.put("B", 1.3);
        Home.test.put("C", 1.4);

        System.out.println(Home.test.get("A");
    }

Upvotes: 2

Related Questions