Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
_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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!