我做了一個小程序來保存我的X和Y值。這裏是我的代碼:內存分配一次或每次在java對象實例化
public class ChartData
{
private Object x, y;
public ChartData(Object x, Object y)
{
this.x = x;
this.y = y;
}
public Object getX()
{
return x;
}
public Object getY()
{
return y;
}
public boolean equals(Object obj)
{
if (obj != null && obj instanceof ChartData)
{
final ChartData other = (ChartData) obj;
if (this.getX().equals(other.getX()) && this.y == null && other.y == null)
{
return true;
}
else if (this.getX().equals(other.getX()) && this.y.equals(other.y))
{
return true;
}
}
return false;
}
public int hashCode()
{
int hashCode = getX().hashCode();
hashCode = (y != null) ? hashCode + y.hashCode() : hashCode ;
return hashCode;
}
}
我想總結的ChartData對象的值(即其持有X和Y值)。 例如: -
LinkedHashMap<ChartData, Object> datasource = new LinkedHashMap<ChartData, Object>();
while(data.next())
{
Object x = data.getValue(1);
Object y = data.getValue(2);
Double value = data.getValue(3);
ChartData cateVal = new ChartData(x, y);
Double currentValue = (Double) datasource.get(cateVal);
if(currentValue != null)
{
datasource.put(cateVal, currentValue + value);
}
else
{
datasource.put(cateVal, value);
}
}
有機會創建一個新的對象相同的X和Y values.Is它實際上爲每個實例創建一個新的對象,否則它使用先前創建memory.Please給我解釋一下。
我相信每次調用'new Xxxx()'時都會在堆上創建一個新對象。現在,如果你對這個對象的唯一引用是一個HashMap,並且它相當於已經在HashMap上的另一個對象,那麼我的直覺告訴我只有一個對象將駐留在Map上,另一個對象應該可用於垃圾收集/當需要出現時。 –