Some of your problems lies here:
ArrayList<String> oldOnes= new ArrayList<String>(); // This line is pointless
oldOnes= os.getAtributo(); // oldOnes will be overwritten here
for (String s : newOnes)
{
oldOnes.add(s);
ObjetoOS newObj = new ObjetoOS(oldOnes);
aux.add(newObj );
newObj = null;
oldOnes.remove(s);
}
When you here pass oldOnes
to the ObjetoOS
constructor, the newObj
will have a reference to the same list as oldOnes
, when you then later remove the element from oldOnes
you also remove it from newObj's
list(since they are the same).
The same does not happen if you use the String
constructor because primitive datatypes, also including Strings
, are copied (passed by value) when passed to a method.
There's a good explanation on how objects are passed in java here: Is Java "pass-by-reference" or "pass-by-value"?
Edit:
Also your tableOS
will point to a new ArrayList<>
every time you call your method, if I understand your solution correctly this might be more what you want:
...
for (ObjetoOS os : tableOS)
{
for (String s : newOnes)
{
ArrayList<String> oldOnesPlusNewOne = new ArrayList<>();
oldOnesPlusNewOne.addAll(os.getAtributo());
oldOnesPlusNewOne.add(s);
ObjetoOS newObj = new ObjetoOS(oldOnesPlusNewOne);
tableOS.add(newObj);
}
}