Getting the memory size out of a class?

I made a class for a tilemap that I want to get the amount of memory it allocates of.

The class looks like this:


import java.awt.*;

public class Tile {

	protected Image tileImage;
	protected int xposition, yposition;
	
	public Tile(Image tile, int x, int y){
		tileImage = tile;
		xposition = x;
		yposition = y;
	}
	
	public Image getImage(){
		return tileImage;
	}
	
	public int getImageWidth(){
		return tileImage.getWidth(null);
	}
	public int getImageHeight(){
		return tileImage.getHeight(null);
	}
}

How do I do this?

I need to create a very large 2D array so I need to know how much each reference of this class takes up.

First: you don’t need to know the size of anything to make a 2d array in java.

Despite that, the size of the reference would be the size of a memory pointer, so afaik 32 or 64 bit depending on CPU-Architecture and JVM.

The size of your class’ instance would be the size of the reference to the image + the size of the two ints. Could be there is some more overhead that the jvm needs for an object instance, but I don’t think so. For the overall memory consumption you need to add the reference to the instance and of course the Image itself.

If you want to dive into this, you could take the time and make yourself comfortable with a java profiler (Netbeans contains one and the standalone VisualVM might have the needed features, too), so you can see exactly what memory your game is using.

As for your tiled engine, it might make more sense to store one image with all tiles and only the coordinates of the rects containing the specific part in your Tile.

Thanks, now that you mention it, using a strip of tiles is indeed much better than having each tile store a reference to an image file, I didn’t think of that.

I wanted to know how much memory one reference of the tile would take up since I plan on creating a very large 2D array of tiles, and I don’t want to consume all my system memory. If it indeed only takes up enough for the variables and the image reference then it wouldn’t be that much ^^