Java 桶排序

标签 java

我正在尝试创建我自己的桶排序风格,但我的代码出现错误,我不知道如何修复它。任何帮助都会很棒。我有两个类,Node 和 BucketSort:

public class Node {

    protected int element;
    protected Node next;

    public Node()
    {
        element = 0;
        next = null;
    }
    public Node getNext(Node n)
    {
        return next;
    }
    public void setNext(Node n)
    {
        n = next;
    }
    public void setElement(int e)
    {
        e = element;
    }
    public int getElement()
    {
        return element;
    }
}

public class BucketSort extends Node{


    public static void bucketSort(int v, int[] b) //b = the array of integers and v = number of buckets wanted. 
    {
        Node[] bucket = new Node[v];  //Creating an array of type Node called bucket with v buckets. 
        for (int i=0; i<=b.length; i++){
            bucket[i].setElement(b[i]);   //Loop through array of integers b, and set each element to the corresponding index of array bucket.
        return;
        }

        for (int i=0; i<=bucket.length; i++){
             //Getting the element at the indexed Node of array "bucket" and assigning it to the array "b" at location element-1. For example if the element is 3, then 3 is assigned to index 2, since it is the 3rd spot.
            b[getElement()-1] = bucket[i].getElement(); 
            return; 
        }
        System.out.println(b);
    }

}

我在 BucketSort 的第 16 行收到以下错误,代码为:b[getElement()-1]

错误是:

不能从类型 Node 对非静态方法 getElement() 进行静态引用。

你能告诉我如何解决这个问题吗?

谢谢

我如何测试这个程序?

最佳答案

问题是您误用了 static 关键字。我不确定你是否熟悉 Java 中静态方法的语义(如果你不熟悉,你应该阅读一些关于它的全面内容,也许 starting here ),但基本思想是一个方法或字段被声明为 static 属于 而不是该类的任何特定实例(对象)。特别是,static 方法没有任何this 指针的概念。

所以问题在于,当您的代码自行调用 getElement() 时,Java 会隐式地将其解释为 this.getElement()。但是,bucketSort()staticgetElement() 属于 Node 的一个实例,所以这不是没有任何意义——调用 getElement() 的到底是什么?

在特定的 Node 对象上调用它,比如 bucket[i],它会编译(虽然还没有真正看到它是否会工作)。

关于Java 桶排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3714418/

相关文章:

java - Spring Data JPA 存储库 Multi-Tenancy 单模式技术

异步完成创建的 Java 对象 - 对象在构造函数完成后的某个时间准备就绪

java - 后缀到中缀 - 括号

java - 由对等方或套接字重置的连接无中生有地关闭

java - 在命令行中使用 javac 编译时出现 "package javax.inject does not exist"错误

java - Java中如何遍历vector只存储指定的类?

java - JavaFX 中的 while 循环导致窗口崩溃

java - 将字节转换为字符串再转换为字节

java - 过滤器链 : java. 的 GlassFish 问题 lang.IllegalStateException: PWC3990: getWriter() 已为此响应调用

java - 有人可以建议一个带有需求规范文档和 junit 测试的开源 java 项目吗?