Java dynamic array sizes?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







85















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?










share|improve this question

























  • I fixed up the formatting of the question, you can just the title if you want, just be descriptive. and welcome to stackoverflow! :D

    – Gordon Gustafson
    Oct 30 '09 at 0:05


















85















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?










share|improve this question

























  • I fixed up the formatting of the question, you can just the title if you want, just be descriptive. and welcome to stackoverflow! :D

    – Gordon Gustafson
    Oct 30 '09 at 0:05














85












85








85


35






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?










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 3 '17 at 21:46









Donnied

58542446




58542446










asked Oct 30 '09 at 0:00









PaulPaul

465265




465265













  • I fixed up the formatting of the question, you can just the title if you want, just be descriptive. and welcome to stackoverflow! :D

    – Gordon Gustafson
    Oct 30 '09 at 0:05



















  • I fixed up the formatting of the question, you can just the title if you want, just be descriptive. and welcome to stackoverflow! :D

    – Gordon Gustafson
    Oct 30 '09 at 0:05

















I fixed up the formatting of the question, you can just the title if you want, just be descriptive. and welcome to stackoverflow! :D

– Gordon Gustafson
Oct 30 '09 at 0:05





I fixed up the formatting of the question, you can just the title if you want, just be descriptive. and welcome to stackoverflow! :D

– Gordon Gustafson
Oct 30 '09 at 0:05












18 Answers
18






active

oldest

votes


















145














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





share|improve this answer





















  • 2





    I use ArrayList instead of List and everything works fine.

    – ConductedClever
    Aug 17 '14 at 18:11











  • List is the interface and ArrayList is the implementation. Creating it as an ArrayList but referring to it as a List (so it can change later) is correct.

    – CBGraham
    Sep 24 '18 at 16:25



















23














In java array length is fixed.



You can use a List to hold the values and invoke the toArray method if needed
See the following sample:



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 {}





share|improve this answer































    8














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





    share|improve this answer

































      6














      You set the number of elements to anything you want at the time you create it:



      xClass mysclass = new xClass[n];


      Then you can initialize the elements in a loop. I am guessing that this is what you need.



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






      share|improve this answer































        6














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





        share|improve this answer































          3














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



          Java API






          share|improve this answer


























          • To be specific: if (i >= mysclass.length) mysclass = Arrays.copyOf(mysclass, i+1); mysclass[i] = new MyClass();

            – Micha Berger
            Aug 30 '17 at 20:39





















          2














          Yes, wrap it and use the Collections framework.



          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.






          share|improve this answer































            2














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






            share|improve this answer































              2














              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.






              share|improve this answer





















              • 4





                Unless you specifically need a thread-safe (-ish) type, you should use ArrayList rather than Vector.

                – Stephen C
                Nov 27 '12 at 13:07



















              1














              Where you declare the myclass array as :



              xClass myclass = new xClass[10]


              , simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.






              share|improve this answer































                0














                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






                share|improve this answer

































                  0














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






                  share|improve this answer































                    0














                    I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:



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


                    this assigns your array size to be the one entered at run time into x.






                    share|improve this answer

































                      0














                      Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.



                      import java.util.Scanner;
                      public class Dynamic {
                      public static Scanner value;
                      public static void main(Stringargs){
                      value=new Scanner(System.in);
                      System.out.println("Enter the number of tests to calculate averagen");
                      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);
                      }
                      }





                      share|improve this answer































                        0














                        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.






                        share|improve this answer































                          0














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


                          }





                          share|improve this answer

































                            0














                            Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).



                            Example:



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


                            Note: available since Java 8.






                            share|improve this answer































                              0














                              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;

                              }





                              share|improve this answer
























                                Your Answer






                                StackExchange.ifUsing("editor", function () {
                                StackExchange.using("externalEditor", function () {
                                StackExchange.using("snippets", function () {
                                StackExchange.snippets.init();
                                });
                                });
                                }, "code-snippets");

                                StackExchange.ready(function() {
                                var channelOptions = {
                                tags: "".split(" "),
                                id: "1"
                                };
                                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                StackExchange.using("externalEditor", function() {
                                // Have to fire editor after snippets, if snippets enabled
                                if (StackExchange.settings.snippets.snippetsEnabled) {
                                StackExchange.using("snippets", function() {
                                createEditor();
                                });
                                }
                                else {
                                createEditor();
                                }
                                });

                                function createEditor() {
                                StackExchange.prepareEditor({
                                heartbeatType: 'answer',
                                autoActivateHeartbeat: false,
                                convertImagesToLinks: true,
                                noModals: true,
                                showLowRepImageUploadWarning: true,
                                reputationToPostImages: 10,
                                bindNavPrevention: true,
                                postfix: "",
                                imageUploader: {
                                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                allowUrls: true
                                },
                                onDemand: true,
                                discardSelector: ".discard-answer"
                                ,immediatelyShowMarkdownHelp:true
                                });


                                }
                                });














                                draft saved

                                draft discarded


















                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1647260%2fjava-dynamic-array-sizes%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown

























                                18 Answers
                                18






                                active

                                oldest

                                votes








                                18 Answers
                                18






                                active

                                oldest

                                votes









                                active

                                oldest

                                votes






                                active

                                oldest

                                votes









                                145














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





                                share|improve this answer





















                                • 2





                                  I use ArrayList instead of List and everything works fine.

                                  – ConductedClever
                                  Aug 17 '14 at 18:11











                                • List is the interface and ArrayList is the implementation. Creating it as an ArrayList but referring to it as a List (so it can change later) is correct.

                                  – CBGraham
                                  Sep 24 '18 at 16:25
















                                145














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





                                share|improve this answer





















                                • 2





                                  I use ArrayList instead of List and everything works fine.

                                  – ConductedClever
                                  Aug 17 '14 at 18:11











                                • List is the interface and ArrayList is the implementation. Creating it as an ArrayList but referring to it as a List (so it can change later) is correct.

                                  – CBGraham
                                  Sep 24 '18 at 16:25














                                145












                                145








                                145







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





                                share|improve this answer















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






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Jan 18 '15 at 17:58









                                JasonMArcher

                                9,442104849




                                9,442104849










                                answered Oct 30 '09 at 0:05









                                cletuscletus

                                512k141843914




                                512k141843914








                                • 2





                                  I use ArrayList instead of List and everything works fine.

                                  – ConductedClever
                                  Aug 17 '14 at 18:11











                                • List is the interface and ArrayList is the implementation. Creating it as an ArrayList but referring to it as a List (so it can change later) is correct.

                                  – CBGraham
                                  Sep 24 '18 at 16:25














                                • 2





                                  I use ArrayList instead of List and everything works fine.

                                  – ConductedClever
                                  Aug 17 '14 at 18:11











                                • List is the interface and ArrayList is the implementation. Creating it as an ArrayList but referring to it as a List (so it can change later) is correct.

                                  – CBGraham
                                  Sep 24 '18 at 16:25








                                2




                                2





                                I use ArrayList instead of List and everything works fine.

                                – ConductedClever
                                Aug 17 '14 at 18:11





                                I use ArrayList instead of List and everything works fine.

                                – ConductedClever
                                Aug 17 '14 at 18:11













                                List is the interface and ArrayList is the implementation. Creating it as an ArrayList but referring to it as a List (so it can change later) is correct.

                                – CBGraham
                                Sep 24 '18 at 16:25





                                List is the interface and ArrayList is the implementation. Creating it as an ArrayList but referring to it as a List (so it can change later) is correct.

                                – CBGraham
                                Sep 24 '18 at 16:25













                                23














                                In java array length is fixed.



                                You can use a List to hold the values and invoke the toArray method if needed
                                See the following sample:



                                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 {}





                                share|improve this answer




























                                  23














                                  In java array length is fixed.



                                  You can use a List to hold the values and invoke the toArray method if needed
                                  See the following sample:



                                  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 {}





                                  share|improve this answer


























                                    23












                                    23








                                    23







                                    In java array length is fixed.



                                    You can use a List to hold the values and invoke the toArray method if needed
                                    See the following sample:



                                    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 {}





                                    share|improve this answer













                                    In java array length is fixed.



                                    You can use a List to hold the values and invoke the toArray method if needed
                                    See the following sample:



                                    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 {}






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Oct 30 '09 at 0:45









                                    OscarRyzOscarRyz

                                    144k99340518




                                    144k99340518























                                        8














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





                                        share|improve this answer






























                                          8














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





                                          share|improve this answer




























                                            8












                                            8








                                            8







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





                                            share|improve this answer















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






                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Oct 30 '09 at 0:44

























                                            answered Oct 30 '09 at 0:30









                                            Stephen CStephen C

                                            526k72586944




                                            526k72586944























                                                6














                                                You set the number of elements to anything you want at the time you create it:



                                                xClass mysclass = new xClass[n];


                                                Then you can initialize the elements in a loop. I am guessing that this is what you need.



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






                                                share|improve this answer




























                                                  6














                                                  You set the number of elements to anything you want at the time you create it:



                                                  xClass mysclass = new xClass[n];


                                                  Then you can initialize the elements in a loop. I am guessing that this is what you need.



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






                                                  share|improve this answer


























                                                    6












                                                    6








                                                    6







                                                    You set the number of elements to anything you want at the time you create it:



                                                    xClass mysclass = new xClass[n];


                                                    Then you can initialize the elements in a loop. I am guessing that this is what you need.



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






                                                    share|improve this answer













                                                    You set the number of elements to anything you want at the time you create it:



                                                    xClass mysclass = new xClass[n];


                                                    Then you can initialize the elements in a loop. I am guessing that this is what you need.



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







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Oct 30 '09 at 0:04









                                                    newacctnewacct

                                                    96k23135197




                                                    96k23135197























                                                        6














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





                                                        share|improve this answer




























                                                          6














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





                                                          share|improve this answer


























                                                            6












                                                            6








                                                            6







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





                                                            share|improve this answer













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






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Dec 18 '13 at 4:28









                                                            Pascal9xPascal9x

                                                            17123




                                                            17123























                                                                3














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



                                                                Java API






                                                                share|improve this answer


























                                                                • To be specific: if (i >= mysclass.length) mysclass = Arrays.copyOf(mysclass, i+1); mysclass[i] = new MyClass();

                                                                  – Micha Berger
                                                                  Aug 30 '17 at 20:39


















                                                                3














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



                                                                Java API






                                                                share|improve this answer


























                                                                • To be specific: if (i >= mysclass.length) mysclass = Arrays.copyOf(mysclass, i+1); mysclass[i] = new MyClass();

                                                                  – Micha Berger
                                                                  Aug 30 '17 at 20:39
















                                                                3












                                                                3








                                                                3







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



                                                                Java API






                                                                share|improve this answer















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



                                                                Java API







                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Feb 10 '17 at 1:31









                                                                chancyWu

                                                                8,44794767




                                                                8,44794767










                                                                answered Apr 15 '13 at 2:54









                                                                man.2067067man.2067067

                                                                10011




                                                                10011













                                                                • To be specific: if (i >= mysclass.length) mysclass = Arrays.copyOf(mysclass, i+1); mysclass[i] = new MyClass();

                                                                  – Micha Berger
                                                                  Aug 30 '17 at 20:39





















                                                                • To be specific: if (i >= mysclass.length) mysclass = Arrays.copyOf(mysclass, i+1); mysclass[i] = new MyClass();

                                                                  – Micha Berger
                                                                  Aug 30 '17 at 20:39



















                                                                To be specific: if (i >= mysclass.length) mysclass = Arrays.copyOf(mysclass, i+1); mysclass[i] = new MyClass();

                                                                – Micha Berger
                                                                Aug 30 '17 at 20:39







                                                                To be specific: if (i >= mysclass.length) mysclass = Arrays.copyOf(mysclass, i+1); mysclass[i] = new MyClass();

                                                                – Micha Berger
                                                                Aug 30 '17 at 20:39













                                                                2














                                                                Yes, wrap it and use the Collections framework.



                                                                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.






                                                                share|improve this answer




























                                                                  2














                                                                  Yes, wrap it and use the Collections framework.



                                                                  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.






                                                                  share|improve this answer


























                                                                    2












                                                                    2








                                                                    2







                                                                    Yes, wrap it and use the Collections framework.



                                                                    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.






                                                                    share|improve this answer













                                                                    Yes, wrap it and use the Collections framework.



                                                                    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.







                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Oct 30 '09 at 0:11









                                                                    Jé QueueJé Queue

                                                                    6,496104356




                                                                    6,496104356























                                                                        2














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






                                                                        share|improve this answer




























                                                                          2














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






                                                                          share|improve this answer


























                                                                            2












                                                                            2








                                                                            2







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






                                                                            share|improve this answer













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







                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered Oct 30 '09 at 0:59









                                                                            sinuhepopsinuhepop

                                                                            13.4k135793




                                                                            13.4k135793























                                                                                2














                                                                                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.






                                                                                share|improve this answer





















                                                                                • 4





                                                                                  Unless you specifically need a thread-safe (-ish) type, you should use ArrayList rather than Vector.

                                                                                  – Stephen C
                                                                                  Nov 27 '12 at 13:07
















                                                                                2














                                                                                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.






                                                                                share|improve this answer





















                                                                                • 4





                                                                                  Unless you specifically need a thread-safe (-ish) type, you should use ArrayList rather than Vector.

                                                                                  – Stephen C
                                                                                  Nov 27 '12 at 13:07














                                                                                2












                                                                                2








                                                                                2







                                                                                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.






                                                                                share|improve this answer















                                                                                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.







                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited Oct 4 '12 at 7:23









                                                                                Jav_Rock

                                                                                17.3k18104160




                                                                                17.3k18104160










                                                                                answered Sep 4 '12 at 18:55









                                                                                Shashank RaghunathShashank Raghunath

                                                                                11413




                                                                                11413








                                                                                • 4





                                                                                  Unless you specifically need a thread-safe (-ish) type, you should use ArrayList rather than Vector.

                                                                                  – Stephen C
                                                                                  Nov 27 '12 at 13:07














                                                                                • 4





                                                                                  Unless you specifically need a thread-safe (-ish) type, you should use ArrayList rather than Vector.

                                                                                  – Stephen C
                                                                                  Nov 27 '12 at 13:07








                                                                                4




                                                                                4





                                                                                Unless you specifically need a thread-safe (-ish) type, you should use ArrayList rather than Vector.

                                                                                – Stephen C
                                                                                Nov 27 '12 at 13:07





                                                                                Unless you specifically need a thread-safe (-ish) type, you should use ArrayList rather than Vector.

                                                                                – Stephen C
                                                                                Nov 27 '12 at 13:07











                                                                                1














                                                                                Where you declare the myclass array as :



                                                                                xClass myclass = new xClass[10]


                                                                                , simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.






                                                                                share|improve this answer




























                                                                                  1














                                                                                  Where you declare the myclass array as :



                                                                                  xClass myclass = new xClass[10]


                                                                                  , simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.






                                                                                  share|improve this answer


























                                                                                    1












                                                                                    1








                                                                                    1







                                                                                    Where you declare the myclass array as :



                                                                                    xClass myclass = new xClass[10]


                                                                                    , simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.






                                                                                    share|improve this answer













                                                                                    Where you declare the myclass array as :



                                                                                    xClass myclass = new xClass[10]


                                                                                    , simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.







                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Oct 30 '09 at 0:05









                                                                                    Amir AfghaniAmir Afghani

                                                                                    29.2k1571114




                                                                                    29.2k1571114























                                                                                        0














                                                                                        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






                                                                                        share|improve this answer






























                                                                                          0














                                                                                          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






                                                                                          share|improve this answer




























                                                                                            0












                                                                                            0








                                                                                            0







                                                                                            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






                                                                                            share|improve this answer















                                                                                            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







                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Dec 6 '15 at 20:19









                                                                                            Mi-Creativity

                                                                                            8,215102943




                                                                                            8,215102943










                                                                                            answered Dec 6 '15 at 20:02









                                                                                            bakzbakz

                                                                                            688




                                                                                            688























                                                                                                0














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






                                                                                                share|improve this answer




























                                                                                                  0














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






                                                                                                  share|improve this answer


























                                                                                                    0












                                                                                                    0








                                                                                                    0







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






                                                                                                    share|improve this answer













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







                                                                                                    share|improve this answer












                                                                                                    share|improve this answer



                                                                                                    share|improve this answer










                                                                                                    answered Dec 12 '15 at 3:25







                                                                                                    user5096772






























                                                                                                        0














                                                                                                        I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:



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


                                                                                                        this assigns your array size to be the one entered at run time into x.






                                                                                                        share|improve this answer






























                                                                                                          0














                                                                                                          I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:



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


                                                                                                          this assigns your array size to be the one entered at run time into x.






                                                                                                          share|improve this answer




























                                                                                                            0












                                                                                                            0








                                                                                                            0







                                                                                                            I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:



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


                                                                                                            this assigns your array size to be the one entered at run time into x.






                                                                                                            share|improve this answer















                                                                                                            I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:



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


                                                                                                            this assigns your array size to be the one entered at run time into x.







                                                                                                            share|improve this answer














                                                                                                            share|improve this answer



                                                                                                            share|improve this answer








                                                                                                            edited Jul 3 '16 at 7:22









                                                                                                            The F

                                                                                                            2,93211225




                                                                                                            2,93211225










                                                                                                            answered Jul 3 '16 at 5:15









                                                                                                            MaranathaMaranatha

                                                                                                            1




                                                                                                            1























                                                                                                                0














                                                                                                                Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.



                                                                                                                import java.util.Scanner;
                                                                                                                public class Dynamic {
                                                                                                                public static Scanner value;
                                                                                                                public static void main(Stringargs){
                                                                                                                value=new Scanner(System.in);
                                                                                                                System.out.println("Enter the number of tests to calculate averagen");
                                                                                                                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);
                                                                                                                }
                                                                                                                }





                                                                                                                share|improve this answer




























                                                                                                                  0














                                                                                                                  Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.



                                                                                                                  import java.util.Scanner;
                                                                                                                  public class Dynamic {
                                                                                                                  public static Scanner value;
                                                                                                                  public static void main(Stringargs){
                                                                                                                  value=new Scanner(System.in);
                                                                                                                  System.out.println("Enter the number of tests to calculate averagen");
                                                                                                                  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);
                                                                                                                  }
                                                                                                                  }





                                                                                                                  share|improve this answer


























                                                                                                                    0












                                                                                                                    0








                                                                                                                    0







                                                                                                                    Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.



                                                                                                                    import java.util.Scanner;
                                                                                                                    public class Dynamic {
                                                                                                                    public static Scanner value;
                                                                                                                    public static void main(Stringargs){
                                                                                                                    value=new Scanner(System.in);
                                                                                                                    System.out.println("Enter the number of tests to calculate averagen");
                                                                                                                    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);
                                                                                                                    }
                                                                                                                    }





                                                                                                                    share|improve this answer













                                                                                                                    Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.



                                                                                                                    import java.util.Scanner;
                                                                                                                    public class Dynamic {
                                                                                                                    public static Scanner value;
                                                                                                                    public static void main(Stringargs){
                                                                                                                    value=new Scanner(System.in);
                                                                                                                    System.out.println("Enter the number of tests to calculate averagen");
                                                                                                                    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);
                                                                                                                    }
                                                                                                                    }






                                                                                                                    share|improve this answer












                                                                                                                    share|improve this answer



                                                                                                                    share|improve this answer










                                                                                                                    answered Nov 26 '16 at 7:07









                                                                                                                    wallace_stevwallace_stev

                                                                                                                    1




                                                                                                                    1























                                                                                                                        0














                                                                                                                        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.






                                                                                                                        share|improve this answer




























                                                                                                                          0














                                                                                                                          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.






                                                                                                                          share|improve this answer


























                                                                                                                            0












                                                                                                                            0








                                                                                                                            0







                                                                                                                            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.






                                                                                                                            share|improve this answer













                                                                                                                            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.







                                                                                                                            share|improve this answer












                                                                                                                            share|improve this answer



                                                                                                                            share|improve this answer










                                                                                                                            answered Feb 1 '17 at 0:57









                                                                                                                            Jatin ChauhanJatin Chauhan

                                                                                                                            113




                                                                                                                            113























                                                                                                                                0














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


                                                                                                                                }





                                                                                                                                share|improve this answer






























                                                                                                                                  0














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


                                                                                                                                  }





                                                                                                                                  share|improve this answer




























                                                                                                                                    0












                                                                                                                                    0








                                                                                                                                    0







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


                                                                                                                                    }





                                                                                                                                    share|improve this answer















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


                                                                                                                                    }






                                                                                                                                    share|improve this answer














                                                                                                                                    share|improve this answer



                                                                                                                                    share|improve this answer








                                                                                                                                    edited Jun 1 '17 at 6:20









                                                                                                                                    Satan Pandeya

                                                                                                                                    2,51531635




                                                                                                                                    2,51531635










                                                                                                                                    answered Jun 1 '17 at 3:51









                                                                                                                                    jyoti bhushanjyoti bhushan

                                                                                                                                    1




                                                                                                                                    1























                                                                                                                                        0














                                                                                                                                        Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).



                                                                                                                                        Example:



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


                                                                                                                                        Note: available since Java 8.






                                                                                                                                        share|improve this answer




























                                                                                                                                          0














                                                                                                                                          Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).



                                                                                                                                          Example:



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


                                                                                                                                          Note: available since Java 8.






                                                                                                                                          share|improve this answer


























                                                                                                                                            0












                                                                                                                                            0








                                                                                                                                            0







                                                                                                                                            Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).



                                                                                                                                            Example:



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


                                                                                                                                            Note: available since Java 8.






                                                                                                                                            share|improve this answer













                                                                                                                                            Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).



                                                                                                                                            Example:



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


                                                                                                                                            Note: available since Java 8.







                                                                                                                                            share|improve this answer












                                                                                                                                            share|improve this answer



                                                                                                                                            share|improve this answer










                                                                                                                                            answered Nov 28 '17 at 22:27









                                                                                                                                            Bosko PopovicBosko Popovic

                                                                                                                                            10125




                                                                                                                                            10125























                                                                                                                                                0














                                                                                                                                                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;

                                                                                                                                                }





                                                                                                                                                share|improve this answer




























                                                                                                                                                  0














                                                                                                                                                  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;

                                                                                                                                                  }





                                                                                                                                                  share|improve this answer


























                                                                                                                                                    0












                                                                                                                                                    0








                                                                                                                                                    0







                                                                                                                                                    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;

                                                                                                                                                    }





                                                                                                                                                    share|improve this answer













                                                                                                                                                    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;

                                                                                                                                                    }






                                                                                                                                                    share|improve this answer












                                                                                                                                                    share|improve this answer



                                                                                                                                                    share|improve this answer










                                                                                                                                                    answered Jul 23 '18 at 3:39









                                                                                                                                                    Chinthaka DevindaChinthaka Devinda

                                                                                                                                                    2612521




                                                                                                                                                    2612521






























                                                                                                                                                        draft saved

                                                                                                                                                        draft discarded




















































                                                                                                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                                                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                                        But avoid



                                                                                                                                                        • Asking for help, clarification, or responding to other answers.

                                                                                                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                                        To learn more, see our tips on writing great answers.




                                                                                                                                                        draft saved


                                                                                                                                                        draft discarded














                                                                                                                                                        StackExchange.ready(
                                                                                                                                                        function () {
                                                                                                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1647260%2fjava-dynamic-array-sizes%23new-answer', 'question_page');
                                                                                                                                                        }
                                                                                                                                                        );

                                                                                                                                                        Post as a guest















                                                                                                                                                        Required, but never shown





















































                                                                                                                                                        Required, but never shown














                                                                                                                                                        Required, but never shown












                                                                                                                                                        Required, but never shown







                                                                                                                                                        Required, but never shown

































                                                                                                                                                        Required, but never shown














                                                                                                                                                        Required, but never shown












                                                                                                                                                        Required, but never shown







                                                                                                                                                        Required, but never shown







                                                                                                                                                        這個網誌中的熱門文章

                                                                                                                                                        Academy of Television Arts & Sciences

                                                                                                                                                        L'Équipe

                                                                                                                                                        1995 France bombings