Java dynamic array sizes?

前端 未结 18 2123
星月不相逢
星月不相逢 2020-11-22 04:37

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


        
相关标签:
18条回答
  • 2020-11-22 05:25

    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());
    
    0 讨论(0)
  • 2020-11-22 05:25

    It is a good practice get the amount you need to store first then initialize the array.

    for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store. if you want a dynamic array you could use ArrayList() and use al.add(); function to keep adding, then you can transfer it to a fixed array.

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

    doing so is redundant but just to show you the idea, ArrayList can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List and Stack

    0 讨论(0)
  • 2020-11-22 05:25

    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]);
            }
        }
    
    
    }
    
    0 讨论(0)
  • 2020-11-22 05:26

    As other users say, you probably need an implementation of java.util.List.

    If, for some reason, you finally need an array, you can do two things:

    • Use a List and then convert it to an array with myList.toArray()

    • Use an array of certain size. If you need more or less size, you can modify it with java.util.Arrays methods.

    Best solution will depend on your problem ;)

    0 讨论(0)
  • 2020-11-22 05:27

    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

    This is the most "used" as well as preferred way to do it-

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

    In the above code we are initializing a new temp[] array, and further using a for loop to initialize the contents of the temp with the contents of the original array ie. stck[]. And then again copying it back to the original one, giving us a new array of new SIZE.

    No doubt it generates a CPU Overhead due to reinitializing an array using for loop repeatedly. But you can still use and implement it in your code. For the best practice use "Linked List" instead of Array, if you want the data to be stored dynamically in the memory, of variable length.

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

    File-name: 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();
    }
    
    }
    

    File-name: 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);
    
    }
    
    }
    

    Hope this solves your query.

    0 讨论(0)
  • 2020-11-22 05:29

    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()]);
    
    0 讨论(0)
提交回复
热议问题