Java 动态数组大小? ?

我有一个 class-xClass,我想将它加载到 xClass 的数组中,因此声明如下:

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

但是,我不知道我是否需要10个。我可能需要8或12或任何其他数字。运行时才能知道。 我可以动态更改数组中的元素数吗? 如果是这样,怎么做?

494363 次浏览

您可以在创建元素时将元素的数量设置为您想要的任何数量:

xClass[] mysclass = new xClass[n];

然后你可以在一个循环中初始化元素。我猜这就是你需要的。

If you need to add or remove elements to the array after you create it, then you would have to use an ArrayList.

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> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());

无论如何,基于以下几个原因,ArrayList是数组的优选解决方案。首先,数组是可变的。如果你有这样的类:

class Myclass {
private int[] items;


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

您已经创建了一个问题,因为调用方可以更改您的私有数据成员,这将导致各种防御性复制。与 List 版本进行比较:

class Myclass {
private List<Integer> items;


public List<Integer> getItems() {
return Collections.unmodifiableList(items);
}
}

Where you declare the myclass[] array as :

xClass myclass[] = new xClass[10]

,只需将所需的 XClass 元素的数量作为参数传入。到那时你知道你需要多少吗?通过将数组声明为包含10个元素,您不是在声明10个 XClass 对象,而是简单地创建一个包含10个 xClass 类型元素的数组。

是的,将它包装起来并使用 Collection 框架。

List l = new ArrayList();
l.add(new xClass());
// do stuff
l.add(new xClass());

Then use List.toArray() when necessary, or just iterate over said List.

正如其他人所说,您不能更改现有 Java 数组的大小。

ArrayList 是标准 Java 中最接近于动态大小数组的数组。然而,有些关于 ArrayList (实际上是 List 接口)的东西并不是“类似于数组”的。例如:

  • 不能使用 [ ... ]索引列表。必须使用 get(int)set(int, E)方法。
  • 创建一个包含零个元素的 ArrayList。您不能简单地创建一个包含20个元素的 ArrayList,然后调用 set(15, foo)
  • 不能直接更改数组列表的大小。您可以使用各种 addinsertremove方法间接完成。

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 当你初始化它的时候, 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()]);

在 java 数组长度是固定的。

您可以使用 List 来保存这些值,并在需要时调用 toArray方法 请参阅下面的示例:

import java.util.List;
import java.util.ArrayList;
import java.util.Random;


public class A  {


public static void main( String [] args ) {
// dynamically hold the instances
List<xClass> list = new ArrayList<xClass>();


// fill it with a random number between 0 and 100
int elements = new Random().nextInt(100);
for( int i = 0 ; i < elements ; i++ ) {
list.add( new xClass() );
}


// convert it to array
xClass [] array = list.toArray( new xClass[ list.size() ] );




System.out.println( "size of array = " + array.length );
}
}
class xClass {}

正如其他用户所说,您可能需要 java.util.List 的实现。

如果出于某种原因,您最终需要一个数组,那么您可以做两件事:

  • 使用 List,然后使用 myList.toArray ()将其转换为数组

  • 使用一定大小的数组。如果需要更大或更小的尺寸,可以使用 java.util 对其进行修改。数组方法。

最好的解决方案将取决于你的问题;)

我推荐使用向量代替。非常容易使用,并且有许多预定义的实现方法。

import java.util.*;


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

要添加一个元素,只需使用:

v.addElement(int);

(5,2)中,前5是矢量的初始大小。如果超过初始大小,向量将增长2位。如果它再次超过,那么它将再次增加2位,以此类推。

Arrays.copyOf()方法有许多选择来解决动态增加 Array 长度的问题。

Java API

你可以使用数组列表:

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());

这是一个很好的实践,先获取需要存储的数量,然后初始化数组。

例如,您可以询问用户需要存储多少数据,然后对其进行初始化,或者查询需要存储多少数据的组件或参数。 如果你想要一个动态数组,你可以使用 ArrayList()和使用 al.add();函数来保持加法,然后你可以把它传输到一个固定的数组。

//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList();
//add a certain amount of data
for(int i=0;i<x;i++)
{
al.add("data "+i);
}


//get size of data inside
int size = al.size();
//initialize String array with the size you have
String strArray[] = new String[size];
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
strArray[i] = al.get(i);
}

这样做是多余的,但只是为了向您展示这个想法,ArrayList可以持有对象不像其他原始数据类型,并且非常容易操作,从中间删除任何东西也很容易,完全动态

Java Array sizes are fixed , You cannot make dynamic Arrays as that of in C++.

我不知道是否可以在运行时更改大小,但是可以在运行时分配大小。尝试使用以下代码:

class MyClass {
void myFunction () {
Scanner s = new Scanner (System.in);
int myArray [];
int x;


System.out.print ("Enter the size of the array: ");
x = s.nextInt();


myArray = new int[x];
}
}

这将数组大小指定为运行时输入到 x 中的数组大小。

这里有一个不使用 ArrayList 的方法。用户指定大小,您可以为递归添加 do-while 循环。

import java.util.Scanner;
public class Dynamic {
public static Scanner value;
public static void main(String[]args){
value=new Scanner(System.in);
System.out.println("Enter the number of tests to calculate average\n");
int limit=value.nextInt();
int index=0;
int [] marks=new int[limit];
float sum,ave;
sum=0;
while(index<limit)
{
int test=index+1;
System.out.println("Enter the marks on test " +test);
marks[index]=value.nextInt();
sum+=marks[index];
index++;
}
ave=sum/limit;
System.out.println("The average is: " + ave);
}
}

In Java Array Sizes are always of Fixed Length But there is way in which you can Dynamically increase the Size of the Array at Runtime Itself

这是最“使用”的,也是最喜欢的方式来做到这一点-

    int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;

在上面的代码中,我们正在初始化一个新的 temp []数组,并进一步使用 for 循环使用原始数组的内容初始化 temp 的内容。[俄语]。然后再将其复制回原始数组,得到一个新的 SIZE 数组。

毫无疑问,它会因为重复使用 for 循环来初始化数组而产生 CPU 开销。但是您仍然可以在代码中使用和实现它。 对于最佳实践,如果您希望数据动态存储在内存中,可变长度的话,可以使用“ Linked List”而不是 Array。

Here's a Real-Time Example based on Dynamic Stacks to INCREASE ARRAY SIZE at Run-Time

文件名: DStack.java

public class DStack {
private int stck[];
int tos;


void Init_Stck(int size) {
stck=new int[size];
tos=-1;
}
int Change_Stck(int size){
return stck[size];
}


public void push(int item){
if(tos==stck.length-1){
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
stck[++tos]=item;
}
else
stck[++tos]=item;
}
public int pop(){
if(tos<0){
System.out.println("Stack Underflow");
return 0;
}
else return stck[tos--];
}


public void display(){
for(int x=0;x<stck.length;x++){
System.out.print(stck[x]+" ");
}
System.out.println();
}


}

文件名: Exec.java
(with the main class)

import java.util.*;
public class Exec {


private static Scanner in;


public static void main(String[] args) {
in = new Scanner(System.in);
int option,item,i=1;
DStack obj=new DStack();
obj.Init_Stck(1);
do{
System.out.println();
System.out.println("--MENU--");
System.out.println("1. Push a Value in The Stack");
System.out.println("2. Pop a Value from the Stack");
System.out.println("3. Display Stack");
System.out.println("4. Exit");
option=in.nextInt();
switch(option){
case 1:
System.out.println("Enter the Value to be Pushed");
item=in.nextInt();
obj.push(item);
break;
case 2:
System.out.println("Popped Item: "+obj.pop());
obj.Change_Stck(obj.tos);
break;
case 3:
System.out.println("Displaying...");
obj.display();
break;
case 4:
System.out.println("Exiting...");
i=0;
break;
default:
System.out.println("Enter a Valid Value");


}
}while(i==1);


}


}

希望这能解决你的疑问。

是的,我们可以这样做。

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]);
}
}




}

由于 ArrayList 在需要基元类型的数组时占用大量内存,因此我更喜欢使用 IntStream.builder ()来创建 int 数组(您也可以使用 LongStream 和 DoubleStream 生成器)。

例如:

Builder builder = IntStream.builder();
int arraySize = new Random().nextInt();
for(int i = 0; i<arraySize; i++ ) {
builder.add(i);
}
int[] array = builder.build().toArray();

注意: 从 Java8开始可用。

You can do some thing

private  static Person []  addPersons(Person[] persons, Person personToAdd) {
int currentLenght = persons.length;


Person [] personsArrayNew = Arrays.copyOf(persons, currentLenght +1);
personsArrayNew[currentLenght]  = personToAdd;


return personsArrayNew;


}

可以创建包含长度变量的数组。就像新的 int [ n ]。并动态地将 n 作为参数传递给 method。您还可以创建可能需要的最大大小的数组。并创建变量来跟踪当前大小。取决于你的用途。