A
A
Andrew2020-06-10 10:46:45
Java
Andrew, 2020-06-10 10:46:45

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<>();


Tell me how to make the map available in other classes or give a link to the source.

Thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Cheremisin, 2020-06-10
@fugro

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;
    }
}

and use
Map<UUID, Person> cache = Singleton.getInstance().getCache();

Well, read on - https://refactoring.guru/ru/design-patterns/single...
Actually, it's better to avoid singletons, and use the so-called DI technique, for example, using spring or guice (my choice). But it's worth starting with singletons.
And of course, the standard singleton is quite simple, you can still make it lazy and add another 20 lines of code - here heads exploded on this topic 10 years ago.

S
Sergey Gornostaev, 2020-06-10
@sergey-gornostaev

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 question

Ask a Question

731 491 924 answers to any question