Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
_Global_ list in Java

I am developing a java program for class, and I have some restrictions that are killing me. I have to read a file and save its words on a list, and then keep that list so I can take words out of it.

I have to read the file and select n words out of the list, and return those words, not the whole list. My question is: is there some way of creating the complete list as global or extern, so every method can access to it, with no need to be a parameter?? I need to be modifying the complete list, removing the words I am needing, and then using it again in other methods.

Thank you :)

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can make a member variable in a class public and static, and that way you can access it from anywhere:

public class One {
    public static List<String> names = new ArrayList<>();
}

public class Two {
    public void addName(String name) {
        One.names.add(name);
    }
}

public class Three {
    public void printTheNames() {
        System.out.println(One.names);
    }
}

However...

These restrictions (like no way to create true global variables) are there for a good reason, and not because Java is lacking features. If you have trouble with these restrictions, then that's a sign you are trying to do things the wrong way - it means the design of your program has problems.

Almost always, global variables are bad.

over 4 years ago · Santiago Trujillo Relatório

0

You can get a globally accessible variable by making it a public static. In terms of design principles, though, this is generally a bad idea because it tends to lead to rampant dependencies that are hard to replace later one.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda