0

Okay, so I have an arraylist declared in my main because elsewhere it brings up an error. However, I want to use that arraylist later specifically to have a getter, but it doesn't recognize the arraylist because it is in my main.

The error is

"it cannot be resolved to a variable"

.

What can I do to correct this?

public static void main(String[] args) {
    ArrayList <String> Strings = new ArrayList <String>(); 
        Strings.add("hi");
        Strings.add("hello");
        Strings.add("goodbye");
}

public ArrayList<String> getArrList() {
        return Strings;
    }
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

3 Answers3

3

You need to make use of the OOP, dont define things static if not needed, use setters and getters and encapsulate the private fields of the classs

Example:

public class Tester {

    private List<String> stringList;

    public Tester() {
        stringList = new ArrayList<String>();
    }

    public void populateList() {
        stringList.add("hi");
        stringList.add("hello");
        stringList.add("goodbye");
    }

    public static void main(String[] args) {
        Tester t = new Tester();
        t.populateList();
        List<> list = t.getList();
        System.out.println( list );
    }

    public List<String> getList(List<String> list) {
        return stringList;
    }
    
    public List<String> setList() {
        return stringList;
    }
}
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • Good answer. The `main` method should have minimal code, just enough to get your app going. Business logic belongs on classes/objects not the `main` method. – Basil Bourque Apr 03 '16 at 15:56
0

You can't call non-static method from static method.

You must define your arraylist as a static variable, then make its getter as static.

static ArrayList <String> Strings;

public static void main(String[] args) {
    Strings = new ArrayList <String>(); 
        Strings.add("hi");
        Strings.add("hello");
        Strings.add("goodbye");
}

public static ArrayList<String> getArrList() {
        return Strings;
}
RJB
  • 32
  • 8
0

Do like this,

class MyClass{
ArrayList <String> Strings;

    public static void main(String[] args) {
        Strings = new ArrayList <String>(); 
        Strings.add("hi");
        Strings.add("hello");
        Strings.add("goodbye");
    }

public ArrayList<String> getArrList() {
      MyClass myClass = new myClass();
        return myClass.Strings;
    }

}
Shree Krishna
  • 8,474
  • 6
  • 40
  • 68