There are some ways. Each one with its advantages and disadvantages. In all cases if the use allows concurrency you will have to control concurrent access by worrying that you do not have a race condition . , for example. I will consider only monothread access that does not require any major concerns.
The simplest way is to create a static variable. Every static variable has a lifetime equal to that of the application and if it has public visibility it can be accessed by any class.
Understand that you have a scope and lifetime issue.
Instance variables have the same lifetime as the instance itself. Statics live by every application.
Instance variables are instance-scoped, so they are accessed through it (it needs to be live and available in the specific scope), since the (static) class variables are class-scoped and accessed through it, which in turn are always in scope in the application.
I think it's clear that no variables can be accessed directly. The scope itself is always encapsulated in a structure (class or instance).
Specific case
I'm not sure what the need is and if this is just an example. There are cases where it would be nice to have a class just for that purpose, perhaps with mechanisms that help you access the data in a more organized way, perhaps a generic class allowing you to store arbitrary data as the application demands.
In this particular case, it seems to me that the simplest way is to only declare vetor
as the static field of the class (it is no longer a local method variable) and will solve the problem in a simple way:
public static int vetor;
This can be accessed from anywhere like:
PesquisaLinearVetor.vetor
Obviously I left without any initialization in the example above, you might want to have a face value already. Remembering that if you try to access this vector like this, the initial value of it will be null. If the intention is to have something, just boot it right there.
If there is any reason not to allow the data to be changed, just enter final
. But there you would have to initialize the variable, otherwise it does not make sense.
Global class
public final class Global {
private Global() {} // só pra garantir que não haja instâncias dela
private static int[] vetor;
public static int[] getVetor() { return vetor; }
public static void setVetor(int[] vetor) { this.vetor = vetor; }
//aqui pode colocar vários outros dados se eles forem relacionados
//o ideal é criar classe gobais para cada necessidade
//nem sempre é necessário usar getter e setter, o campo público pode ser suficiente
//é possível criar outras operações específicas de acordo com a necessidade
//por exemplo pode pegar e setar um elemento do vetor
In this case, always use Global.getVetor() e fazer o que quiser
and Global.setVetor(um vetor de int aqui)
.
}
Note that I would say that the simplest solution that is to leave a static field in the class you are already using is more appropriate in most cases. If you already have a good place to put one, why create another?
Singleton
On the other hand keeping global access open in this way may not be the most appropriate.
Some people prefer, for some reasons, to have a Singleton class than a pure static. It can be done too, you have the limitation that you always need to "instantiate" the class to use the value, but the data will be global in the same way.
Some considerations about Singleton and the global state as a whole:
HashMap
This is a more generic option that allows you to secure multiple global data in an easy and dynamic way.
public class DataHolder {
private static Map<String, WeakReference<Object>> data = new HashMap<String, WeakReference<Object>>();
public static void save(String id, Object object) {
data.put(id, new WeakReference<Object>(object));
}
public static Object retrieve(String id) {
WeakReference<Object> objectWeakReference = data.get(id);
return objectWeakReference.get();
}
}
Of course this can be improved as needed. In the background the mechanism is always the same - there is a static variable storing the value, here only an extra mechanism has been added to generalize in case the problem requires multiple global data on demand (which does not seem to be the case for the question) / p>
In-memory database
Depending on the need you can use a database yourself. Some work exclusively in memory and do not need installation. That's the case with SQLite .