简体   繁体   English

使用循环Java创建链接列表的链接列表数组

[英]Create an Linked List array of linked lists with a loop java

I have successfully implemented Radix sort but I have the following code that I would like to convert to be created by a loop. 我已经成功实现了Radix排序,但是我想将以下代码转换为通过循环创建。

private static LinkedList[] bucket = { 
        new LinkedList(), // -9
        new LinkedList(), // -8
        new LinkedList(), // -7
        new LinkedList(), // -6
        new LinkedList(), // -5
        new LinkedList(), // -4
        new LinkedList(), // -3
        new LinkedList(), // -2
        new LinkedList(), // -1
        new LinkedList(), // 0
        new LinkedList(), // 1
        new LinkedList(), // 2
        new LinkedList(), // 3
        new LinkedList(), // 4
        new LinkedList(), // 5
        new LinkedList(), // 6
        new LinkedList(), // 7
        new LinkedList(), // 8
        new LinkedList() // 9
};

However I cannot figure out how I might go about doing this. 但是,我不知道该怎么做。 I tried this but I get compiler errors. 我试过了,但是出现编译器错误。

private static LinkedList[] bucket;
int thing = 19;
while(thing != 0){
    bucket = new LinkedList();
    thing--;
}

This is not critical to the functionality of my radix sort as it works flawlessly, I just think it would be cleaner to initialize my buckets with a loop. 这对我的基数排序功能至关重要,因为它可以完美地工作,我只是认为用循环初始化存储桶会更干净。 That said if someone could enlighten me on how to do this I would be very grateful. 就是说,如果有人可以启发我如何做,我将不胜感激。

Here you go: 干得好:

private static LinkedList[] bucket = new LinkedList[19];

static {
    for (int i = 0; i < bucket.length; ++i) {
        bucket[i] = new LinkedList();
    }
}

Your LinkedList[] bucket is not initlaized,so you will get NullPointerException at runtime.Also,the syntax of array element assignment is wrong 您的LinkedList[]存储桶未初始化,因此您将在运行时获取NullPointerException 。此外,数组元素分配的语法错误

private static LinkedList[] bucket = new LinkedList[20];
int thing = 19;
while(thing != 0){
    bucket[thing] = new LinkedList();
    thing--;
}

First set up how big the array is going to be (how many LinkedList s are going to be in it), then iterate from zero to that size, and set indices of the array to be new LinkedList s. 首先设置数组的大小(将要包含多少LinkedList ),然后从零开始迭代到该大小,并将数组的索引设置为新的LinkedList

For example, if i is your iterator variable, you would say: 例如,如果i是您的迭代器变量,您会说:

bucket[i] = new LinkedList();

Remember what types you're dealing with: a single LinkedList , and an array of them. 记住要处理的类型:一个LinkedList以及它们的数组。 You can't just assign the entire array to one LinkedList . 您不能只将整个数组分配给一个LinkedList You have to assign the elements to LinkedList s, to match types. 您必须将元素分配给LinkedList ,以匹配类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM