Java dynamic array sizes?

2018-12-31 07:49发布

I have a class - xClass, that I want to load into an array of xClass so I the declaration:

xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();

However, I don't know if I will need 10. I may need 8 or 12 or any other number for that matter. I won't know until runtime. Can I change the number of elements in an array on the fly? If so, how?

标签: java
18条回答
皆成旧梦
2楼-- · 2018-12-31 08:30

You can use ArrayList:

import java.util.ArrayList;
import java.util.Iterator;

...

ArrayList<String> arr = new ArrayList<String>();
arr.add("neo");
arr.add("morpheus");
arr.add("trinity");
Iterator<String> foreach = arr.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());
查看更多
梦醉为红颜
3楼-- · 2018-12-31 08:34

No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:

int oldItems[] = new int[10];
for (int i=0; i<10; i++) {
  oldItems[i] = i+10;
}
int newItems[] = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;

If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList essentially wraps an array and takes care of the logic for growing the array as required:

List<xClass> mysclass = new ArrayList<xClass>();
myclass.add(new xClass());
myclass.add(new xClass());

Generally an ArrayList is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:

class Myclass {
  private int items[];

  public int[] getItems() { return items; }
}

you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:

class Myclass {
  private List<Integer> items;

  public List<Integer> getItems() { return Collections.unmodifiableList(items); }
}
查看更多
深知你不懂我心
4楼-- · 2018-12-31 08:35

As others have said, you cannot change the size of an existing Java array.

ArrayList is the closest that standard Java has to a dynamic sized array. However, there are some things about ArrayList (actually the List interface) that are not "array like". For example:

  • You cannot use [ ... ] to index a list. You have to use the get(int) and set(int, E) methods.
  • An ArrayList is created with zero elements. You cannot simple create an ArrayList with 20 elements and then call set(15, foo).
  • You cannot directly change the size of an ArrayList. You do it indirectly using the various add, insert and remove methods.

If you want something more array-like, you will need to design your own API. (Maybe someone could chime in with an existing third party library ... I couldn't find one with 2 minutes "research" using Google :-) )

If you only really need an array that grows as you are initializing it, then the solution is something like this.

ArrayList<T> tmp = new ArrayList<T>();
while (...) {
    tmp.add(new T(...));
}
// This creates a new array and copies the element of 'tmp' to it.
T[] array = tmp.toArray(new T[tmp.size()]);
查看更多
与君花间醉酒
5楼-- · 2018-12-31 08:35

Arrays.copyOf() method has many options to fix the problem with Array length increasing dynamically.

Java API

查看更多
高级女魔头
6楼-- · 2018-12-31 08:35

Yes, we can do this way.

import java.util.Scanner;

public class Collection_Basic {

    private static Scanner sc;

    public static void main(String[] args) {

        Object[] obj=new Object[4];
        sc = new Scanner(System.in);


        //Storing element
        System.out.println("enter your element");
        for(int i=0;i<4;i++){
            obj[i]=sc.nextInt();
        }

        /*
         * here, size reaches with its maximum capacity so u can not store more element,
         * 
         * for storing more element we have to create new array Object with required size
         */

        Object[] tempObj=new Object[10];

        //copying old array to new Array

        int oldArraySize=obj.length;
        int i=0;
        for(;i<oldArraySize;i++){

            tempObj[i]=obj[i];
        }

        /*
         * storing new element to the end of new Array objebt
         */
        tempObj[i]=90;

        //assigning new array Object refeence to the old one

        obj=tempObj;

        for(int j=0;j<obj.length;j++){
            System.out.println("obj["+j+"] -"+obj[j]);
        }
    }


}
查看更多
不流泪的眼
7楼-- · 2018-12-31 08:36

I recommend using vectors instead. Very easy to use and has many predefined methods for implementation.

import java.util.*;

Vector<Integer> v=new Vector<Integer>(5,2);

to add an element simply use:

v.addElement(int);

In the (5,2) the first 5 is the initial size of the vector. If you exceed the initial size,the vector will grow by 2 places. If it exceeds again, then it will again increase by 2 places and so on.

查看更多
登录 后发表回答