Java动态数组大小?

Java动态数组大小?,java,Java,我有一个类-xClass,我想将它加载到一个xClass数组中,因此我需要声明: xClass mysclass[] = new xClass[10]; myclass[0] = new xClass(); myclass[9] = new xClass(); 但是,我不知道我是否需要10个。我可能需要8或12或任何其他数字。直到运行时我才知道。 我可以动态更改数组中的元素数吗? 如果是,如何设置?您可以在创建元素时将元素数设置为所需的任何值: xClass[] mysclass = new

我有一个类-xClass,我想将它加载到一个xClass数组中,因此我需要声明:

xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();
但是,我不知道我是否需要10个。我可能需要8或12或任何其他数字。直到运行时我才知道。 我可以动态更改数组中的元素数吗?
如果是,如何设置?

您可以在创建元素时将元素数设置为所需的任何值:

xClass[] mysclass = new xClass[n];
然后可以初始化循环中的元素。我猜这就是你需要的


如果在创建数组后需要向数组中添加或删除元素,则必须使用
ArrayList

否创建数组后,无法更改数组的大小。您要么必须将其分配得比您认为需要的更大,要么必须接受重新分配以增加其规模所需的开销。如果需要,您必须分配一个新的,并将数据从旧数据复制到新数据:

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;
通常情况下,
ArrayList
是数组的首选解决方案,原因有几个。首先,数组是可变的。如果您有这样的类:

class Myclass {
    private int[] items;

    public int[] getItems() {
        return items;
    }
}
您已经造成了一个问题,因为调用者可以更改您的私有数据成员,这会导致各种防御性复制。将其与列表版本进行比较:

class Myclass {
    private List<Integer> items;

    public List<Integer> getItems() {
        return Collections.unmodifiableList(items);
    }
}
class-Myclass{
私人清单项目;
公共列表getItems(){
返回集合。不可修改列表(项目);
}
}

其中您将myclass[]数组声明为:

xClass myclass[] = new xClass[10]

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

是的,将其包装并使用集合框架

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

然后在必要时使用List.toArray(),或者只是在所述列表上迭代。

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

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

  • 不能使用
    […]
    为列表编制索引。您必须使用
    get(int)
    set(int,E)
    方法
  • ArrayList是用零个元素创建的。您不能简单地创建一个包含20个元素的ArrayList,然后调用
    set(15,foo)
  • 不能直接更改ArrayList的大小。您可以使用各种
    add
    insert
    remove
    方法间接执行此操作
如果您想要更像数组的东西,则需要设计自己的API。(也许有人可以加入现有的第三方图书馆……我找不到一个有2分钟“研究”时间的图书馆,使用Google:-)

如果您只需要一个在初始化时增长的数组,那么解决方案是这样的

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()]);
ArrayList tmp=new ArrayList();
而(…){
tmp.add(新T(…);
}
//这将创建一个新数组并将“tmp”元素复制到该数组中。
T[]数组=tmp.toArray(新的T[tmp.size()]);

在java中,数组长度是固定的

如果需要,您可以使用列表保存值并调用
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 {}
import java.util.List;
导入java.util.ArrayList;
导入java.util.Random;
公共A类{
公共静态void main(字符串[]args){
//动态保存实例
列表=新的ArrayList();
//用0到100之间的随机数填充它
int elements=new Random().nextInt(100);
for(int i=0;i
正如其他用户所说,您可能需要java.util.List的实现

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

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

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


最佳解决方案取决于您的问题;)

我建议改用向量。非常容易使用,并且有许多预定义的实现方法

import java.util.*;

Vector<Integer> v=new Vector<Integer>(5,2);
在(5,2)中,前5是向量的初始大小。如果超出初始大小,向量将增加2个位置。如果它再次超过,那么它将再次增加2个位置,以此类推。

Arrays.copyOf()
方法有许多选项来解决数组长度动态增加的问题

您可以使用ArrayList:

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

ArrayList arr=new ArrayList();
arr.add(“neo”);
arr.add(“morpheus”);
arr.add(“trinity”);
迭代器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并转换字符串,以便ArrayList接受字符串(或任何内容
ArrayList al=新的ArrayList();
//添加一定数量的数据

对于(int i=0;i java数组大小是固定的,不能用C++中的动态数组来做。

< p>我不知道在运行时是否可以改变大小,但是可以在运行时分配大小。试试这个代码:

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的大小。

这里有一个不使用Ar的方法
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());
//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);
}
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];
    }
}
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);
        }
    }
    int temp[]=new int[stck.length+1];
    for(int i=0;i<stck.length;i++)temp[i]=stck[i];
    stck=temp;
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();
}

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


}
Builder builder = IntStream.builder();
int arraySize = new Random().nextInt();
for(int i = 0; i<arraySize; i++ ) {
    builder.add(i);
}
int[] array = builder.build().toArray();
private  static Person []  addPersons(Person[] persons, Person personToAdd) {
    int currentLenght = persons.length;

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

    return personsArrayNew;

}