It has some forms. Each one with its advantages and disadvantages. In all if the use allows competition will have to control simultaneous access worrying that it does not have a running condition, for example. I will consider only access monothread that requires no further concern.
The simplest way is to create a static variable. Every static variable has the same lifespan as the application and if it has public visibility it can be accessed by any class.
Understand that there is a question of life span and time.
Instance variables have the same lifetime as the instance itself. Static variables live throughout the application.
Instance variables have instance scope (object), so they are accessed through it (it needs to be alive and available in the specific scope), whereas class variables (static) have class scope and accessed through it, which in turn are always in scope in the application.
Behold What is the difference between a class and an object?.
I think it’s clear that no variable can be accessed directly. Their scope itself is always encapsulated in a structure (class or instance).
Specific case
I’m not sure what the need is and if that’s just an example. There are cases that it would be good to have a class only for this purpose, perhaps with mechanisms that help access the data in a more organized way, perhaps a generic class allowing to store arbitrary data as the demand of the application.
In this particular case it seems to me that the simplest way is just to declare vetor
as a static field of the class (no longer a local variable of the method) and will solve the problem simply:
public static int vetor;
This can be accessed from anywhere like:
PesquisaLinearVetor.vetor
Obviously I left without any initialization in the above example, it may be that I wish to have an already expensive value. Remember that if you try to access this vector then its initial value will be null. If the intention is to have something just initialize it right there.
If there is any reason not to allow the data to be changed just put as final
. But then it would require initializing the variable, otherwise it makes no 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 globais 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
}
I put in the Github for future reference.
In that case, just wear it at all times Global.getVetor() e fazer o que quiser
and Global.setVetor(um vetor de int aqui)
.
I would say that the simplest solution that is to leave a static field in the class you are already using is more suitable in most cases. If you already have a good place to put a die, why create another?
Singleton
On the other hand, maintaining global open access in this way may not be the most appropriate.
Some people prefer, for some reasons, to have a Singleton class rather than pure static. It can also be done, it has the limitation that always needs 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 hold 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();
}
}
I put in the Github for future reference.
Of course this can be improved as needed. In the background the mechanism is always the same - there is a static variable guarding the value, here has only been added an extra mechanism to generalize to the case of the problem require several global data on demand (which does not seem to be the case of the question).
Database in-memory
Depending on the need it is possible to use even a database. Some work exclusively in memory and do not need installation, is the case with Sqlite.
It is also possible to change the contents of the variable?
– gato
Yes, it can, as long as it’s not
final
.– Maniero
Global.gerVetor works even if it is not a static method?
– user28595
Oops. Now it’s okay.
– Maniero