简体   繁体   中英

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.

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.

For that you will have to use List or ArrayList .

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.

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. 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 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.

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.

You can hand roll your own if you can't use a List using System.arraycopy

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...

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). However, accessing elements for inserting and deleting in a linked list is not efficient (O(n) time). 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.

The Java ArrayList is an implementation of a dynamic array. 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:

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. I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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