java - 这个功能是如何使用的?

标签 java function

我正在学习我的讲师给我的几门类(class),我不明白函数 heapRebuild 是如何使用的!它不会更改任何全局变量,也不会打印出任何内容,也不会返回任何内容——所以这应该有效吗?不应该,应该吗?

如果您被告知要使用 heapRebuild 来创建一个新函数 removeMac,您会编辑 heapRebuild 吗?

public class MaxHeap<T extends Comparable<T>> implements Heap<T>{
private T[] heap;
private int lastIndex;

public T removeMax(){
        T rootItem = heap[0];
        heap[0] = heap[lastIndex-1];
        lastIndex--;
        heapRebuild(heap, 0, lastIndex);
        return rootItem;
}

protected void heapRebuild(T[ ] items, int root, int size){

        int child = 2*root+1;
        if( child < size){
            int rightChild = child+1;
            if ((rightChild < size) &&
                    (items[rightChild].compareTo(items[child]) > 0)){
                child = rightChild;
            }
            if (items[root].compareTo(items[child]) < 0){
                T temp = items[root];
                items[root] = items[child];
                items[child] = temp;
                heapRebuild(items, child, size);}
        }
    }

最佳答案

Java 是一种按值传递引用的 OO 语言。这些方法可以更改传入的可变值。

简化示例:

import java.util.Arrays;

public class Test {

    public static void main(String... args) {
        String[] strings = new String[] { "foo", "bar" };
        System.out.println(Arrays.toString(strings)); // [foo, bar]
        changeValue(strings);
        System.out.println(Arrays.toString(strings)); // [foo, foo]
    }

    public static void changeValue(String[] strings) {
        strings[1] = "foo";
    }

}

关于java - 这个功能是如何使用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709945/

相关文章:

java - 插入、替换/更新 JDBC

java - Java中负数相减的问题

javascript - 函数内部调用函数的作用域

c++ - Boost::Function 和 Boost::Bind 的替代方案

java - 对如何调用类内的方法感到困惑

java - Spring + Maven + Intellij +HelloWorld

java - 使用资源包的单元测试静态方法

c - 警告从默认启用的不兼容指针类型传递参数 1 of ""

javascript - 使用函数作为回调还是存储它?

mysql - mysql中使用伪递归函数优化查询