Integer obj = new Integer(5); WeakReferenceref = new WeakReference (obj); obj = null; //Remove the strong reference to the Integer object Integer value = ref.get(); //Get the weakly reference object if (value == null) { System.out.println("The object has been collected by the garbage collector"); } else { System.out.println("The object is still available"); }
HashMapThis code creates a `HashMap` to store weak references to `MyObject` instances. After adding a weak reference to the map, the strong reference to the `MyObject` instance is removed. The `get()` method is used to retrieve the weak reference from the map, and the `get()` method is used to retrieve the object from the weak reference. If the object has been garbage collected, then the `get()` method will return null. The `java.lang.ref` package is part of the Java Core API.> map = new HashMap<>(); MyObject obj = new MyObject(); map.put("key", new WeakReference (obj)); obj = null; //Remove the strong reference to the MyObject instance WeakReference ref = map.get("key"); MyObject value = ref.get(); if (value == null) { System.out.println("The object has been collected by the garbage collector"); } else { System.out.println("The object is still available"); }