首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java Bucket排序

Java Bucket排序
EN

Stack Overflow用户
提问于 2010-09-15 11:18:11
回答 2查看 2.1K关注 0票数 1

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

代码语言:javascript
复制
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;
    }
}

代码语言:javascript
复制
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行收到以下错误,is代码: bgetElement()-1

错误是:

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

你能告诉我怎么解决这个问题吗。

谢谢

如何测试此程序?

EN

回答 2

Stack Overflow用户

发布于 2010-09-15 11:23:52

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

所以问题是,当你的代码自己调用getElement()时,Java会隐式地将其解释为this.getElement()。但是,bucketSort()static,而getElement()属于Node的一个实例,所以这没有任何意义--调用getElement()的确切原因是什么?

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

票数 3
EN

Stack Overflow用户

发布于 2010-09-15 11:36:23

查看错误。它会告诉你所犯的错误。

您可以为特定对象调用getElement()

为什么bucketSort(int v, int[] b)需要是静态的?有什么原因吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3714418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档