It is possible, but it will be less efficient than a simple wrapper class with a List
field.
Following your comments on @BlaiseDoughan's answer, here is your SaveableList
implementation. Basically what you need is a class which implements List
and forwards all calls to an internal List
implementation, e.g. ArrayList
. In my example I extend AbstractList
for simplicity.
SaveableList
implementation:
class SaveableList extends AbstractList<String> {
@XmlElement(name="e")
private final List<String> list = new ArrayList<>();
@Override
public String get(int index) {
return list.get(index);
}
@Override
public boolean add(String e) {
return list.add(e);
}
@Override
public int size() {
return list.size();
}
// You might want to implement/override other methods which you use
// And is not provided by AbstractList
}
Example usage:
List<String> list = new SaveableList();
list.add("one");
list.add("two");
// Save it to XML
JAXB.marshal(list, new File("list.xml"));
// Load it from XML:
List<String> list2 = JAXB.unmarshal(new File("list.xml"), SaveableList.class);
Here is the XML it generates:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<saveableList>
<e>one</e>
<e>two</e>
</saveableList>