有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (5) 个答案

  1. # 1 楼答案

    您不能在java中创建悬挂指针,因为没有显式释放内存的机制

  2. # 2 楼答案

    这取决于你对悬挂指针的定义

    如果你接受维基百科对悬挂指针的定义,那么不,你不能在Java中使用它。因为语言是垃圾收集的,所以引用将始终指向有效对象,除非您显式地为引用指定“null”

    但是,你可以考虑悬空指针的语义版本。 “语义悬空引用”如果你愿意的话。 使用此定义,可以引用物理上有效的对象,但在语义上该对象不再有效

    String source = "my string";
    String copy = source;
    
    if (true == true) {
        // Invalidate the data, because why not
        source = null;
        // We forgot to set 'copy' to null!
    }
    
    // Only print data if it hasn't been invalidated
    if (copy) {
        System.out.println("Result: " + copy)
    }
    

    在本例中,“copy”是一个物理上有效的对象引用,但在语义上它是一个悬空引用,因为我们想将其设置为null,但忘记了。 结果是,使用“copy”变量的代码将毫无问题地执行,即使我们打算使其无效

  3. # 3 楼答案

    并非在所有JVM上都可用,但Sun的JVM确实提供了sun.misc.unsafe#allocateMemory(long bytes)。该调用返回一个指针

    释放内存。您的初始指针现在“悬空”

  4. # 4 楼答案

    根据下面的Wikipedias definition没有

    Dangling pointers and wild pointers in computer programming are pointers that do not point to a valid object of the appropriate type.

    Dangling pointers arise when an object is deleted or deallocated, without modifying the value of the pointer, so that the pointer still points to the memory location of the deallocated memory

    如果某个引用仍然指向(1),则无法删除(或“垃圾收集”,如果您愿意)

    在上面的维基百科文章中,你可以进一步阅读:

    In languages like Java, dangling pointers cannot occur because there is no mechanism to explicitly deallocate memory. Rather, the garbage collector may deallocate memory, but only when the object is no longer reachable from any references.

    使引用指向(“有效”)对象的唯一方法是为其指定null

    (1)除非它是例如WeakReference,但该引用在垃圾收集时无效

  5. # 5 楼答案

    String foo = null;
    

    如果你试着说foo.substring(0),你会得到一个^{}

    你是什么意思