views:

51

answers:

1

Hi, I was wondering if someone could explain how the following code works:

public interface Result {
  public int getCount();
  public List<Thing> getThings();
}


class SomeClass {
...
  public Result getThingResult() {
    final List<Thing> things = .. populated from something.

    final int count = 5;

    return new Result {
      @Override
      public int getCount() {
        return count;
      }

      @Override
      public List<Thing> getThings();
        return things;
      }
    }
  }
...
}

Where do the primitive int , List reference and List instance get stored in memory? It can't be on the stack.. so where? Is there a difference between how references and primitives are handled in this situation?

Thanks a bunch, Tim P.

+3  A: 

The used final locals (and any outer this references) are copied to synthetic fields of the inner class during construction. References and primitives are, as always, treated the same. Both are (shallow) copied.

You can use javap from the JDK to see what is being generated.

Tom Hawtin - tackline
...which is why they have to be final: so that nobody can tell that the variables are simply copied.
Michael Borgwardt
@Michael It would, of course, be possible to quietly do extra allocations to store mutable state on the heap.
Tom Hawtin - tackline
@Michael: You can hack your way past the finality by using arrays (or any other container; a `Holder` would work well enough). Messy, but works.
Donal Fellows
Thanks Tom, Micheal and Donal, That explains it clearly. I'll take a look at javap when I have time.Using Apaches Mutable... classes helped me here.
Tim P