Supernaturalgirl 1967
Supernaturalgirl 1967

Reputation: 289

How to call an Arraylist method?

I have a method:

public static ArrayList<Integer>Iterate(int n){
    ArrayList<Integer> numbers = new ArrayList<Integer>(n);{
        Random rand = new Random();
        rand.setSeed(System.currentTimeMillis());
        for(int i = 0; i<n; ++i){
            Integer r = rand.nextInt() %113;
            numbers.add(r);
            Collections.sort(numbers);
        }}

And I want to use other methods on this Array to find out certain things about the numbers.

But I can't figure out to call the Arraylist in public static void main(String [] args).

I've tried things like:

System.out.println( numbers.methodname); 

And things like that, but Eclipse says numbers cannot be resolved to a variable So what's the proper way to call the ArrayList so a method can effect it?

Upvotes: 0

Views: 13505

Answers (3)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

You probably want to make your method return the ArrayList that it creates, so that it can be used by whatever method called your method. You've already got the right method signature - that is, the first line, where it says

public static ArrayList<Integer> Iterate(int n){

which means that the method will return something of type ArrayList<Integer>. Now you need to add this line to the bottom of the method, before the last }.

return numbers;

Now, within your main method, or whatever other method calls this one, you can write something like

ArrayList<Integer> returnedList = Iterate(10);

or something similar, depending on what number you want to pass to the method. This declares a variable called returnedList, calls the method, and assigns the ArrayList that's returned by the method, to the variable that you declared.

Upvotes: 1

Tiberiu
Tiberiu

Reputation: 1030

numbers needs to be declared outside of your method for other methods to be able to access it. If you declare a variable inside a method, its scope is the method it was declared in.

You can still initialize the variable inside the method if you so choose, but the declaration has to be made outside, like this:

ArrayList<Integer> numbers = null;

public static ArrayList<Integer> Iterate(int n){
    numbers = new ArrayList<Integer>(n);
    // code
}

Upvotes: 0

Alex Monroe
Alex Monroe

Reputation: 51

Since you declared the numbers variable in the Iterate method, it does not exist outside the scope of that method. This means that while you're in main, you cannot access that variable. If you want to access a variable in main, it needs to be declared in main.

Upvotes: 0

Related Questions