I have two ArrayLists
. As below example shows.
ArrayList<String> listVarName = new ArrayList<String>();
ArrayList<String> listVarValue = new ArrayList<String>();
listVarName.add("One");
listVarName.add("Two");
listVarName.add("Three");
listVarName.add("Four");
listVarValue.add("Content of One");
listVarValue.add("Content of Two");
listVarValue.add("Content of Three");
listVarValue.add("Content of Four");
//Code to append the value
int index = listVarName.indexOf("Two");
String oldVal = listVarValue.get(index);
listVarValue.remove(index);
listVarValue.add(index, oldVal+" APPENDED TEXT");
System.out.println(listVarName.toString());
System.out.println(listVarValue.toString());
Output Before appending:
[One, Two, Three, Four]
[Content of One, Content of Two, Content of Three, Content of Four]
Output after appending:
[One, Two, Three, Four]
[Content of One, Content of Two APPENDED TEXT, Content of Three, Content of Four]
In above code listVarName is key and listVarValue is value.
So I am trying to append listVarValue
where its index matches the index of listVarName
. So I am getting old value of listVarValue
and adding new value to it and then removing old value from list and inserting new value to its old position.
Above code is working fine. My question is that is there any better way instead the code I have used to append the value?
Assuming you're concerned about the list modification rather than general structure, yes - there's a better way.
Rather than using remove
then add
, use List.set(index, element)
:
String oldVal = listVarValue.get(index);
listVarValue.set(index, oldVal + " APPENDED TEXT");
As well as being simpler code, this is more efficient - adding and removing in an ArrayList
each involve copying all the rest of the elements within the backing array to their new position - whereas set
just involves changing a single element in the backing array.
See more on this question at Stackoverflow