Mokkapps
Mokkapps

Reputation: 2028

ArrayList final in android

I want to make my ArrayList with custom objects final so that the objects cannot be changed after they are set.

I tried to declare it like this:

private final ArrayList<Datapoint> XML = new ArrayList<Datapoint>();

I fill the ArrayList with this lines:

FileInputStream fileIn = new FileInputStream(f);
ObjectInputStream in = new ObjectInputStream(fileIn);
XML = (ArrayList<Datapoint>) in.readObject();
in.close();
fileIn.close();

and this for-loop to show the objects:

for(int i=0;i<XML.size();i++){
                    item = XML.get(i);      
                    parsedData = parsedData + "----->\n";
                    parsedData = parsedData + "Name: " + item.getName() + "\n";
                    parsedData = parsedData + "stateBased: " + item.getStateBased() + "\n";
                    parsedData = parsedData + "mainNumber: " + item.getMainNumber() + "\n";
                    parsedData = parsedData + "dptID: "+ item.getDptID() + "\n";
                    parsedData = parsedData + "Groupadress: "+ item.getGroupadress() + "\n";
                    parsedData = parsedData + "priority: "+ item.getPriority() + "\n";
                }

xmlOutput.setText(parsedData);

But Eclipse says The final field XMLDetailsActivity.XML cannot be assigned.

What is the problem?

Upvotes: 0

Views: 527

Answers (4)

AlexR
AlexR

Reputation: 115368

final keyword just mean that the reference to the object cannot be changed. It does not mean however that you cannot call the object's method that changes its state.

This can be achieved for list by using Collections.unmodifiableList().

Upvotes: 2

zmbq
zmbq

Reputation: 39023

Your XML variable is final, and yet you try to assign it another value: XML = ...in.readObject(); You can't do that.

Also, note that a final ArrayList means you can't replace the ArrayList, you can still call its methods to modify its content, final is not C++'s const.

Upvotes: 1

Daniel
Daniel

Reputation: 3806

You are trying to assign a new value to your XML variable. As you declare it final before this, you cannot reassign it.

Upvotes: 0

Dan D.
Dan D.

Reputation: 32391

Once the final variable has been assigned a value, you can no longer assign another value.

The final member variables must be assigned values before the constructor of the class they belong to has finished executing.

Upvotes: 0

Related Questions