Reputation: 8724
If I have an ArrayList of Objects in Java, is the underlying implementation really just an array of object references? I'm creating this method:
//method returns all combinations of Objects
public ArrayList<ArrayList<Object>> getAllCombinations(ArrayList<Object> allObjects){
}
As I started thinking about the problem, I wondered if I could just return an ArrayList<ArrayList<Integer>>
where the ints were the position in allObjects (essentially thinking this would use drastically less memory). But then I started thinking that each value of the array implementation just points to the memory location of the objects in the and that the array wasn't creating new objects for each ArrayList I was creating (which would definitely use more memory). So in reality, it would use about the same memory if I just implement the method I mentioned above, right?
I think I need to understand Java's memory allocation a little bit better...
Upvotes: 0
Views: 65
Reputation: 328568
Yes, an array or an arraylist only contains references to objects, not the objects themselves. So each item in your array uses 4 bytes of memory (on a 32 bit machine), regardless of the size of the underlying objects.
So keep it simple and return whatever makes sense.
Upvotes: 1
Reputation: 14842
You got that right: The elements of your ArrayList
will only point to the objects (except if you copy them explicitly). So both implementations will use about the same memory as you say.
This is by the way something important to consider, if you want to alter the state of your objects as they will also seem altered in the old array where they originated from.
Upvotes: 1