简体   繁体   中英

How can I reference / define an array from another method in java?

I have some code that is similar to the following:

public class exampleClass {

    public void main(){
        defineVariable();
        nextMethod();
    }

    void nextMethod(){
        list[8] = "threw away";
    }

    void defineVariable(){
        String[] list = {"trivial string","more trivial strings",
                       "just another trivial string","tr","a","sd",
                       "godzilla","ate","my","pony","and homework","trivial"};
    }

}

And I cant access list in nextMethod.How can I fix this problem , it may seem trivial to make such a small array global but the actual arrays are in the hundreds (hence the fact I didnt c+p my actual code although if this is necessary I wont mind in the least).

Thanks very much and as a side note this is in Android although I doubt that that will effect the java code (am I wrong to assume this?).

Anyway thanks again! Ive been using StackOverflow alot lately and have only contributed a bit so from now on I will attempt to answer as many questions as I can.

Thanks,

Simply declare it in class.

 public class exampleClass {

    public void main()
    {

    nextMethod(defineVariable());
    }

    void nextMethod(String[] list)
    {
    list[8] = "threw away";
    }

    private String tab[] defineVariable()
    {
    String[] list= {"trivial string","more trivial strings","just another trivial string","tr","a","sd",
                     "godzilla","ate","my","pony","and homework","trivial"};
       return list
    }

    }

If you let defineVariable be void and create a variable within its own scope, that variable just disappears into oblivion upon finished exection. Instead, have defineVariable return the list and then use this list as a parameter to the nextMethod() function.

A neat way to store many variables is to group them into different objects. That way variables that are related can be put into the same object and the number of variables in your main class is reduced to a managable number.

In the example below, I have made the variables public. If you prefer, you can create getters and setters instead.

public class Actions {
  public String humans[] = { "sit", "stand", "eat", "walk", "run", "drive", ride" };
  public String dogs[] = { "sit", "stand", "bark", "run" };
  public String sharks[] = { "swim", "attack" };
}

public class Equipment {
  public String armour[] = { "leather", "chainmail", "plate" };
  public String weapon[] = { "sword", "axe", "dagger" };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM