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?
finalkeyword 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().