java - Create new object vs setting its variables inside a function -
i have rectangle class , constructor sets every variable (x, y, width, height) specific value. after rectangle being created, if want change of values. that, more efficient have function rect.set(newx, newy, newwidth, newheight); or call constructor r1 = new rectangle(newx, newy, newwidth, newheight); on again ? (since won't referencing older rectangle anymore) public rectangle (int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public void set (int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } i imagine creating new rectangle create garbage, should worse. true ? or java somehow optimize ? this rather old question. highly dependent on task. of course, creating object has overhead comparing mutating existent object, in cases negligible. overall creating new objects preferable way design point of view. hotspot jvm ...