如何在不使用预制类的情况下在 Java 中创建可扩展的动态数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2914281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:25:57  来源:igfitidea点击:

How to create extensible dynamic array in Java without using pre-made classes?

javadynamicarraysrealloc

提问by AndrejaKo

Yeah, it's a homework question, so givemetehkodezplsthx! :)

是的,这是一个家庭作业问题,所以给metehkodezplsthx!:)

Anyway, here's what I need to do:
I need to have a class which will have among its attributes array of objects of another class. The proper way to do this in my opinion would be to use something like LinkedList, Vector or similar. Unfortunately, last time I did that, I got fire and brimstone from my professor, because according to his belief I was using advanced stuff without understanding basics.

无论如何,这就是我需要做的:
我需要一个类,该类将包含另一个类的对象的属性数组。在我看来,正确的方法是使用 LinkedList、Vector 或类似的东西。不幸的是,上次我这样做时,我从教授那里得到了火和硫磺,因为根据他的信念,我在不了解基础知识的情况下使用高级东西。

Now next obvious solution would be to create array with fixed number of elements and add checks to get and set which will see if the array is full. If it is full, they'd create new bigger array, copy older array's data to the new array and return the new array to the caller. If it's mostly empty, they'd create new smaller array and move data from old array to new. To me this looks a bit stupid. For my homework, there probably won't be more that 3 elements in an array, but I'd like to make a scalable solution without manually calculating statistics about how often is array filled, what is the average number of new elements added, then using results of calculation to calculate number of elements in new array and so on.

现在下一个明显的解决方案是创建具有固定元素数量的数组,并添加检查以查看数组是否已满。如果它已满,他们将创建新的更大的数组,将旧数组的数据复制到新数组并将新数组返回给调用者。如果它大部分是空的,他们会创建新的较小的数组并将数据从旧数组移动到新数组。对我来说,这看起来有点愚蠢。对于我的作业,数组中的元素可能不会超过 3 个,但我想制作一个可扩展的解决方案,而无需手动计算有关数组填充频率的统计信息,添加的新元素的平均数量是多少,然后使用计算结果来计算新数组中元素的数量等。

By the way, there is no need to remove elements from the middle of the array.

顺便说一句,不需要从数组中间删除元素。

Any tips?

有小费吗?

回答by Andrei Fierbinteanu

class test {
    private Object[] objects;
    private int size;

    public test() {
        objects = new Object[10];
        size = 0;
    }

    public void push(Object o) {
        if (objects.length == size) {
            throw new RuntimeException("This wouldn't happen if I didn't have to reinvent the wheel");
        }
        objects[size] = o;
        size++;
    }

    public Object pop() {
        size--;
        Object o = objects[size];
        objects[size] = null;
        return o;
    }
}

Just kidding. I think you're best bet is to implement your own linked list and then use that in your class. Something like:

只是在开玩笑。我认为你最好的办法是实现你自己的链表,然后在你的课堂上使用它。就像是:

class Element {
    Object val;
    Element next;
    Element prev;

    public Element(Object val, Element next, Element prev) {
        this.val = val;
        this.next = next;
        this.prev = prev;
    }

}

class LinkedList {
    Element head;
    Element tail;

    public void add(Object o) {
        Element el = new Element(o, null, tail);
        tail.next = el;
    }

    public Object remove() {
        Element o = tail;
        tail = o.prev;
        tail.next = null;
        return o.val;
    }
}

回答by jjnguy

One thing you will want to do is when you need to grow the size of your array create an array that is twice the size of the old array. Likewise, if you need to shrink the size of hte array, only do it once the array is half full.

您需要做的一件事是,当您需要增加数组的大小时,创建一个大小为旧数组两倍的数组。同样,如果您需要缩小 hte 数组的大小,请仅在数组半满时执行。

This will make it so you have to do far less array copies.

这将使您不必做更少的数组副本。

Doing this will make it necessary to keep a variable that keeps track of the actual size of the array because the length of the array will not accurately represent the actual size.

这样做将需要保留一个变量来跟踪数组的实际大小,因为数组的长度不会准确表示实际大小。

回答by BalusC

To copy an existing array into a smaller or larger one, you may find System#arrayCopy()useful.

要将现有数组复制到更小或更大的数组中,您可能会发现System#arrayCopy()很有用。

Kickoff example:

开场示例:

Object[] originalArray = new Object[3];
// ...
Object[] resizedArray = new Object[originalArray.length + 2]; // Grow with 2.
System.arrayCopy(originalArray, 0, resizedArray, 0, originalArray.length);

This will copy the items over the entire length of originalArrayinto the beginning of resizedArray. The 2 slots at end of resizedArrayare still nullso that you can use it for other items.

这会将整个长度上的项目复制originalArray到 的开头resizedArray。末尾的 2 个插槽resizedArray仍然存在,null以便您可以将其用于其他项目。

This must get you started. Good luck :)

这必须让你开始。祝你好运 :)

回答by sjobe

Is it for a data structures class ? Sounds like your professor expects you to implement your own Linked Listdata structure or something similar instead of using the one Java provides. Google and your text book(s) are your friend.

是用于数据结构类吗?听起来您的教授希望您实现自己的链表数据结构或类似的东西,而不是使用 Java 提供的一种。Google 和您的教科书是您的朋友。

回答by Moonshield

If I recall correctly, the ArrayList class works by having a fixed size array (with an initial capacity of whatever you set) that resizes in pretty much the way you described when it's full.

如果我没记错的话,ArrayList 类通过具有固定大小的数组(具有您设置的任何初始容量)来工作,该数组在它已满时几乎按照您描述的方式调整大小。

You could use a linked list, though by the sounds of it your professor wants you to program this stuff by yourself, so create your own class demonstrating you know how it works?

您可以使用链表,尽管听起来您的教授希望您自己编写这些东西,因此创建您自己的课程来证明您知道它是如何工作的?

回答by Muhammad Abubakar

i think its really easy way :p which we cant do in C but can do in java

我认为它真的很简单:p 我们不能用 C 做但可以用 Java 做

package javaapplication21;

import java.util.Scanner;
public class JavaApplication21 {
    public static void main(String[] args) {
       int a;
       Scanner obj=new Scanner(System.in);
       System.out.print("Enter array size=");
       a=obj.nextInt();
       int b[]=new int[a];
       for(int i=0;i<b.length;i++){
          System.out.println(b[i]+i);
       }
   }
}