简体   繁体   English

如何在Java中创建动态数组?

[英]How can I make a dynamic array in Java?

Quick overview of our assignment: User needs to enter grades received. 我们的作业快速概览:用户需要输入收到的成绩。 We do not know how many grades user needs to enter. 我们不知道用户需要输入多少个等级。 If the user enters "-1" thats when we know the user is done entering grades. 如果用户输入“ -1”,则表示我们已经完成输入成绩。

Problem is how do you use a counter and assign values to an array in the same loop? 问题是如何使用计数器并在同一循环中将值分配给数组? I would rather not have to ask the user to enter all values twice (Once to get array size and the second time to assign grades to index positions). 我宁愿不必要求用户两次输入所有值(一次获得数组大小,第二次为索引位置分配等级)。

Our professor gave us a handout that tells us to basically guess the size of the array and hope for the best. 我们的教授给了我们一份讲义,告诉我们基本上可以猜测数组的大小并希望达到最佳效果。 I refuse to believe that's the only solution. 我拒绝相信这是唯一的解决方案。

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

You can't make dynamic array in java. 您不能在Java中创建动态数组。

For that you will have to use List or ArrayList . 为此,您将必须使用ListArrayList

We will have to provide the size of array before application run or at coding time, while arrayList gives us facility to add data while we need it, so it's size will automatically increased when we add data. 我们将必须在应用程序运行之前或在编码时提供数组的大小,而arrayList为我们提供了在需要时添加数据的便利,因此添加数据时它的大小会自动增加。

Example : 范例:

import java.util.*;

public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
      ArrayList al = new ArrayList();
      System.out.println("Initial size of al: " + al.size());

      // add elements to the array list
      al.add("C");
      al.add("A");
      al.add("E");
      al.add("B");
      al.add("D");
      al.add("F");
      al.add(1, "A2");
      System.out.println("Size of al after additions: " + al.size());

      // display the array list
      System.out.println("Contents of al: " + al);
      // Remove elements from the array list
      al.remove("F");
      al.remove(2);
      System.out.println("Size of al after deletions: " + al.size());
      System.out.println("Contents of al: " + al);
   }
}

this example is from here. 这个例子是从这里开始的。

UPDATE : 更新:

When you define your list as: 当您将列表定义为:

List myList = new ArrayList(); you can only call methods and reference members that belong to List class. 您只能调用属于List类的方法和引用成员。 If you define it as: 如果将其定义为:

ArrayList myList = new ArrayList(); you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List. 除了从List继承的成员之外,您还可以调用ArrayList特定的方法并使用ArrayList特定的成员。

List is not a class it is an interface. 列表不是类,而是接口。 It doesn't have any methods implemented. 它没有实现任何方法。 So if you call a method on a List reference, you in fact calling the method of ArrayList in both cases. 因此,如果您在List引用上调用方法,则实际上在两种情况下都将调用ArrayList的方法。

Using some kind of List is a better choice, as it basically does what you want (can grow and shrink), in fact, ArrayList is just that, a dynamic array. 使用某种List是一个更好的选择,因为它基本上可以完成您想要的(可以增长和收缩),实际上, ArrayList就是一个动态数组。

You can hand roll your own if you can't use a List using System.arraycopy 如果不能使用System.arraycopyList则可以自己滚动

For example, this will grow or shrink an array to match the size you provide... 例如,这将增加或缩小数组以匹配您提供的大小。

public String[] updateArray(String[] src, int size) {

    String[] dest = new String[size];
    if (size > src.length) {

        System.arraycopy(src, 0, dest, 0, src.length);

    } else {

        System.arraycopy(src, 0, dest, 0, size);

    }

    return dest;

}

Again... List is easier... 再次... List更容易...

Building a dynamic array involves these basic steps: 构建动态数组涉及以下基本步骤:

-Create an array of a fixed capacity. -创建固定容量的数组。

-When the size of the array (# of elements added) approach the capacity, create a new array (usually doubling the capacity), and copy all the old elements to the new array. -当数组的大小(添加的元素数)接近容量时,创建一个新的数组(通常将容量增加一倍),然后将所有旧元素复制到新数组中。

A linked list is the most efficient for your task of building the array (done in O(1) time). 链表对于构建阵列(完成时间为O(1))最有效。 However, accessing elements for inserting and deleting in a linked list is not efficient (O(n) time). 但是,访问用于在链表中插入和删除的元素的效率不高(O(n)时间)。 Imagine having to move through the whole list to get to the last element. 想象一下,必须遍历整个列表才能到达最后一个元素。 Building the dynamic array is less efficient, because of the need to re-size the array as it grows. 构建动态数组的效率较低,因为需要随着数组的增长调整其大小。 Inserting and deleting elements is less efficient because of need to move all the elements after to make room or fill the gap. 插入和删除元素的效率较低,因为需要在此之后移动所有元素以腾出空间或填补空白。 However accessing an element in an array is efficient (O(1) time) and there are big advantages when it comes to sorting. 但是,访问数组中的元素效率很高(O(1)时间),在排序时有很大的优势。

The Java ArrayList is an implementation of a dynamic array. Java ArrayList是动态数组的实现。 You could also implement your own. 您也可以实现自己的。

If you can't use an ArrayList, or any kind of dynamic list at all, then one solution would be this: 如果您根本无法使用ArrayList或任何类型的动态列表,那么一个解决方案是:

StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(System.in);
int j;
while((j=scanner.nextInt()) !=-1){
    sb.append(j + " ");
}
String []numbers = sb.toString().split(" ");
int[] grades = new int[numbers.length];
for(int i=0;i<numbers.length;i++){
    grades[i] = Integer.parseInt(numbers[i]);
}

As you can see, I'm putting the input in a stringbuilder object, then I parse it in an array of strings, and convert that array in an integer array. 如您所见,我将输入放入stringbuilder对象中,然后将其解析为字符串数组,然后将该数组转换为整数数组。 I hope this helps. 我希望这有帮助。

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

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