Answer the question
In order to leave comments, you need to log in
How to access HashMap from other classes?
Hey!
I am creating a simple console application that reads data from a txt file and writes it to another file. After reading, I place the data in the map.
I want to make it so that the user can add a new element to the map himself, and then write it to a file.
Faced with a lack of understanding of how to make my map static and available in all other classes except Reader. That is, you need to make a centralized cache.
public static ConcurrentHashMap<UUID, Person> cache = new ConcurrentHashMap<>();
Answer the question
In order to leave comments, you need to log in
You make a singleton class and put everything you need to rummage around in it (you initialize everything in a private constructor).
public final class Singleton {
private static Singleton instance;
private final ConcurrentHashMap<UUID, Person> cache; // не static!
public Map<UUID, Person> getCache() {
return cache;
}
private Singleton() {
this.cache = new ConcurrentHashMap<>()
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Map<UUID, Person> cache = Singleton.getInstance().getCache();
Instead of making it available in all other classes, make the class that contains it have methods for adding and getting data from it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question