1 回答

TA貢獻(xiàn)1785條經(jīng)驗 獲得超4個贊
Java 保存對象的引用,您可以將其視為指針。您只是不能像 C 中的指針那樣對引用進(jìn)行任何算術(shù)運算。因此,此代碼顯示了兩個引用同一競爭對手的 CompetitorInEvent:
class CompetitorInEvent {
private Competitor competitor;
public CompetitorInEvent(Competitor competitor) {
this.competitor = competitor;
}
}
然后使用這個:
Competitor aCompetitor = new Competitor();
CompetitorInEvent event1 = new CompetitorInEvent(aCompetitor);
CompetitorInEvent event2 = new CompetitorInEvent(aCompetitor);
現(xiàn)在只實例化了一個 Competitor,并有 3 個對它的引用:局部變量 aCompetitor 和兩個事件。請注意,Java 維護(hù)對象的引用計數(shù),并且不會垃圾收集(銷毀)aCompetitor,直到局部變量超出范圍(或重新分配給另一個引用),并且兩個 CompetitorInEvent 對象都被銷毀/垃圾收集。
添加回答
舉報