joanlopez
joanlopez

Reputation: 589

How to get an element of a non-final ArrayList?

I've a class Persona with:

String name;
Int age;

And I have an ArrayList<Persona>, then

I fill the ArrayList with a for loop which add(new Persona(name,age)) with a JSON parse data (this JSON parsing is from a PHP request to a MySQL DB which returns a random number of "Persona's").

When the loop finish, I want to get one of this Persona's, but Eclipse IDE said to me that to use get(i) I have to declare the ArrayList like final, and if I do that, I can't fill it.

This is the code:

ArrayList<Persona> personas = new ArrayList<Persona>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);

try {
    personas = json.getJSONArray(TAG);
    for(int i = 0; i < putas.length(); i++) {
        JSONObject c = personas.getJSONObject(i);
        String name = c.getString(TAG_NAME);
        Int age = c.getString(TAG_AGE);
        personas.add(new Persona(name, age));
} catch (...) {
    ...
}

int i = 4;
Persona p = personas.get(i);

With this code, IDE show me an error and "offers" me to add the "final" modifier to the ArrayList, but it's absurd.

PD: The problem is with an Android application, but I think that it's a Java problem.

Upvotes: 0

Views: 181

Answers (3)

Raedwald
Raedwald

Reputation: 48682

final is not the same as C++ const. Declaring personas to be a final reference does not prevent you altering the object that reference refers to.

Upvotes: 1

Richard Taylor
Richard Taylor

Reputation: 2752

There should be no reason that it won't compile unless you make it final there. You must be missing something out.

Either way, the final keyword simply means that you can't assign something to that field any more, not that you can't call its methods.

You're right in that, if you made personas final then your code as it stands won't work, because personas = json.getJSONArray(TAG) would not be allowed.

Since you're getting a complaint about being non-final when compiling, I'm assuming that you actually have some code after this, which uses personas. If you're trying to use that inside something like this:

Runnable r = new Runnable() { public void run() { personas.get(0); } };

Which you might be doing for a View listener or something.

That, would require you to make it final. The easiest solution to that would be just to make another local variable, and have that one be final.

final ArrayList<Persona> finalPersonas = personas

Upvotes: 0

Srinivas B
Srinivas B

Reputation: 1852

try initialising the array List in the try block...

 ArrayList<Persona> personas;
 JSONParser jParser;
 JSONObject json;
 try
 {
   personas = new ArrayList<Persona>();
   jParser = new JSONParser();
   json = jParser.getJSONFromUrl(url);

   // rest of the code
 }
 catch(Exception e){}

Upvotes: 0

Related Questions