Java i Garbage collector - ciekawe zadanie

1

Znalazłem na necie takie zadanie:

import java.util.*;
public class Grasshopper {

    public Grasshopper(String n) {
        name = n;
    }

    public static void main(String[] args) {
        Grasshopper one = new Grasshopper("g1");
        Grasshopper two = new Grasshopper("g2");
        one = two; //linia 9
        two = null; //linia 10
        one = null; //linia 11
    }

    private String name;
}

Które ze zdań są poprawne:

A. Immediately after line 9, no grasshopper objects are eligible for garbage collection.
B. Immediately after line 10, no grasshopper objects are eligible for garbage collection.
C. Immediately after line 9, only one grasshopper object is eligible for garbage collection.
D. Immediately after line 10, only one grasshopper object is eligible for garbage collection.
E. Immediately after line 11, only one grasshopper object is eligible for garbage collection.
F. The code compiles.
G. The code does not compile.

Poprawne to ponoć: C, D, F.

Czy jest ktoś mi w stanie to wytłumaczyć, bo nie bardzo to rozumiem?

0

Nie podałeś numerów linii.
Jeżeli linia 9 to "Grasshopper two = new Grasshopper("g2");", to poprawne są:
A D E F

0

A -> new Grasshopper("g1"); juz nie ma referencji więc jest do GC
B -> patrz A)
C -> patrz A)
D -> mamy cały czas referencje do jednego grashoppera w zmiennej one
E -> teraz nie ma juz żadnych referencji wiec oba obiekty do GC
F-> nie trzeba chyba wyjaśniać ;]

0

to jest ciekawe o_O
Jeżeli chcesz więcej tego typu pytań ogarnij sobie temat OCA/OCPJP.

1 użytkowników online, w tym zalogowanych: 0, gości: 1