I know this is a dumb question, but its really bugging me.
Take the following:
public <TParseable> LinkedList<TParseable> readAllParseable(
Parseable<TParseable> parseable, boolean close) throws IOException
{
LinkedList<TParseable> list = new LinkedList<TParseable>();
byte[] delim = parseable.getDelimiterValue();
boolean skipNL = parseable.skipNewLines();
while(ready())
{
byte[] data = readTo(delim);
parseable.parse(data);
System.out.println(parseable);
list.add((TParseable)parseable);
}
return list;
}
The println statement outputs the expected toString() value of parseable each time after the call to parseable.parse(data). However, the returned list has the correct number of elements, but they are all equal to the last value of parseable before the loop completed.
Is this because the list.add(xxx) parameter is passed by pointer rather than value?
You only ever have a single instance of
parseablein the code you posted. When you calladd(parseable)you are adding a reference (“pointer” isn’t really correct in Java) toparseablein your list.By calling it repeatedly, without changing what object
parseablerefers to, you are simply adding more references to the same object to your list.New objects are only ever created by the
newkeyword.