How to add new elements to an array?add an element to int [] array in javaadd string to String arrayHow can I add new item to the String array?Add an object to an Array of a custom classAdd a File object to an array of File objectsHow to add new element into an arrayAdding object into object arrayHow to add elements to String array on AndroidHow to add element to this array?How to add object to arrayHow to check if a string contains a substring in BashHow to append something to an array?How do I generate random integers within a specific range in Java?Sort array of objects by string property valueHow to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?Why is subtracting these two times (in 1927) giving a strange result?How can I add new array elements at the beginning of an array in Javascript?Why is it faster to process a sorted array than an unsorted array?

Mage Armor with Defense fighting style (for Adventurers League bladeslinger)

How old can references or sources in a thesis be?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Email Account under attack (really) - anything I can do?

Why Is Death Allowed In the Matrix?

What's the output of a record cartridge playing an out-of-speed record

To string or not to string

Theorems that impeded progress

What typically incentivizes a professor to change jobs to a lower ranking university?

How does strength of boric acid solution increase in presence of salicylic acid?

Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?

How is it possible to have an ability score that is less than 3?

TGV timetables / schedules?

How could an uplifted falcon's brain work?

Why are 150k or 200k jobs considered good when there are 300k+ births a month?

An academic/student plagiarism

Prove that NP is closed under karp reduction?

"You are your self first supporter", a more proper way to say it

How to find program name(s) of an installed package?

How can I make my BBEG immortal short of making them a Lich or Vampire?

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

Mathematical cryptic clues

Do I have a twin with permutated remainders?

strToHex ( string to its hex representation as string)



How to add new elements to an array?


add an element to int [] array in javaadd string to String arrayHow can I add new item to the String array?Add an object to an Array of a custom classAdd a File object to an array of File objectsHow to add new element into an arrayAdding object into object arrayHow to add elements to String array on AndroidHow to add element to this array?How to add object to arrayHow to check if a string contains a substring in BashHow to append something to an array?How do I generate random integers within a specific range in Java?Sort array of objects by string property valueHow to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?Why is subtracting these two times (in 1927) giving a strange result?How can I add new array elements at the beginning of an array in Javascript?Why is it faster to process a sorted array than an unsorted array?






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








250















I have the following code:



String[] where;
where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


Those two appends are not compiling. How would that work correctly?










share|improve this question






























    250















    I have the following code:



    String[] where;
    where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
    where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


    Those two appends are not compiling. How would that work correctly?










    share|improve this question


























      250












      250








      250


      67






      I have the following code:



      String[] where;
      where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
      where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


      Those two appends are not compiling. How would that work correctly?










      share|improve this question
















      I have the following code:



      String[] where;
      where.append(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
      where.append(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


      Those two appends are not compiling. How would that work correctly?







      java arrays string






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 13 '13 at 5:11









      Paul Bellora

      46k15113164




      46k15113164










      asked May 16 '10 at 10:37









      Pentium10Pentium10

      132k101360437




      132k101360437






















          17 Answers
          17






          active

          oldest

          votes


















          357














          The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.



          A better solution would be to use an ArrayList which can grow as you need it. The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.



          List<String> where = new ArrayList<String>();
          where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
          where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );


          If you need to convert it to a simple array...



          String[] simpleArray = new String[ where.size() ];
          where.toArray( simpleArray );


          But most things you do with an array you can do with this ArrayList, too:



          // iterate over the array
          for( String oneItem : where )
          ...


          // get specific items
          where.get( 1 );





          share|improve this answer




















          • 7





            What's the point in using Array if you can do the same with ArrayList?

            – Skoua
            Jan 11 '17 at 15:44






          • 5





            @Skoua speed!!!

            – vishalknishad
            Sep 22 '17 at 6:37











          • @tangens.I am new to android but your answer helped me.before finding answer i wasted many hours

            – vision
            Aug 27 '18 at 15:42


















          92














          Use a List<String>, such as an ArrayList<String>. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).



          import java.util.*;
          //....

          List<String> list = new ArrayList<String>();
          list.add("1");
          list.add("2");
          list.add("3");
          System.out.println(list); // prints "[1, 2, 3]"


          If you insist on using arrays, you can use java.util.Arrays.copyOf to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.



          static <T> T[] append(T[] arr, T element) 
          final int N = arr.length;
          arr = Arrays.copyOf(arr, N + 1);
          arr[N] = element;
          return arr;


          String[] arr = "1", "2", "3" ;
          System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
          arr = append(arr, "4");
          System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"


          This is O(N) per append. ArrayList, on the other hand, has O(1) amortized cost per operation.



          See also




          • Java Tutorials/Arrays

            • An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.


          • Java Tutorials/The List interface





          share|improve this answer

























          • You can double the size of the array every time the capacity is not enough. That way append will be amortized O(1). Probably what ArrayList does internally.

            – Siyuan Ren
            Jan 24 '14 at 7:55


















          19














          There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.



          String[] array1 = new String[]"one", "two";
          String[] array2 = new String[]"three";
          String[] array = new String[array1.length + array2.length];
          System.arraycopy(array1, 0, array, 0, array1.length);
          System.arraycopy(array2, 0, array, array1.length, array2.length);





          share|improve this answer
































            17














            Apache Commons Lang has



            T[] t = ArrayUtils.add( initialArray, newitem );


            it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.






            share|improve this answer






























              12














              There is no method append() on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.



              List<String> where = new ArrayList<String>();
              where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
              where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


              Or if you are really keen to use an array:



              String[] where = new String[]
              ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
              ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
              ;


              but then this is a fixed size and no elements can be added.






              share|improve this answer























              • So does a parameterized query accept ArrayList as selectionArgs as well?

                – Skynet
                Oct 19 '15 at 14:19


















              7














              String[] source = new String[] "a", "b", "c", "d" ;
              String[] destination = new String[source.length + 2];
              destination[0] = "/bin/sh";
              destination[1] = "-c";
              System.arraycopy(source, 0, destination, 2, source.length);

              for (String parts : destination)
              System.out.println(parts);






              share|improve this answer






























                6














                As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.



                String[] where = new String[10];


                This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a
                dynamically growing collection, use the ArrayList.






                share|improve this answer






























                  5














                  You need to use a Collection List. You cannot re-dimension an array.






                  share|improve this answer






























                    4














                    If you would like to store your data in simple array like this



                    String[] where = new String[10];


                    and you want to add some elements to it like numbers please us StringBuilder which is much more efficient than concatenating string.



                    StringBuilder phoneNumber = new StringBuilder();
                    phoneNumber.append("1");
                    phoneNumber.append("2");
                    where[0] = phoneNumber.toString();


                    This is much better method to build your string and store it into your 'where' array.






                    share|improve this answer






























                      4














                      Adding new items to String array.



                      String[] myArray = new String[] "x", "y";

                      // Convert array to list
                      List<String> listFromArray = Arrays.asList(myArray);

                      // Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
                      List<String> tempList = new ArrayList<String>(listFromArray);
                      tempList.add("z");

                      //Convert list back to array
                      String[] tempArray = new String[tempList.size()];
                      myArray = tempList.toArray(tempArray);





                      share|improve this answer

























                      • Ah, I see, you used the <code> tag and this had problems with the generic types. Please try to avoid this tag, since ... it has problems, and indent your code with 4 whitespaces to get the proper formatting. I did that for your question :).

                        – Tom
                        Dec 11 '15 at 17:09


















                      4














                      I've made this code! It works like a charm!



                      public String[] AddToStringArray(String[] oldArray, String newString)

                      String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
                      newArray[oldArray.length] = newString;
                      return newArray;



                      I hope you like it!!






                      share|improve this answer
































                        4














                        There are many ways to add an element to an array. You can use a temp List to manage the element and then convert it back to Array or you can use the java.util.Arrays.copyOf and combine it with generics for better results.



                        This example will show you how:



                        public static <T> T[] append2Array(T[] elements, T element)

                        T[] newArray = Arrays.copyOf(elements, elements.length + 1);
                        newArray[elements.length] = element;

                        return newArray;



                        To use this method you just need to call it like this:



                        String[] numbers = new String[]"one", "two", "three";
                        System.out.println(Arrays.toString(numbers));
                        numbers = append2Array(numbers, "four");
                        System.out.println(Arrays.toString(numbers));


                        If you want to merge two array you can modify the previous method like this:



                        public static <T> T[] append2Array(T[] elements, T[] newElements)

                        T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
                        System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);

                        return newArray;



                        Now you can call the method like this:



                        String[] numbers = new String[]"one", "two", "three";
                        String[] moreNumbers = new String[]"four", "five", "six";
                        System.out.println(Arrays.toString(numbers));
                        numbers = append2Array(numbers, moreNumbers);
                        System.out.println(Arrays.toString(numbers));


                        As I mentioned, you also may use List objects. However, it will require a little hack to cast it safe like this:



                        public static <T> T[] append2Array(Class<T[]> clazz, List<T> elements, T element)

                        elements.add(element);
                        return clazz.cast(elements.toArray());



                        Now you can call the method like this:



                        String[] numbers = new String[]"one", "two", "three";
                        System.out.println(Arrays.toString(numbers));
                        numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
                        System.out.println(Arrays.toString(numbers));





                        share|improve this answer
































                          3














                          I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size.
                          You have to use an ArrayList or a Vector or any other dynamic structure.






                          share|improve this answer






























                            2














                            you can create a arraylist, and use Collection.addAll() to convert the string array to your arraylist






                            share|improve this answer






























                              2














                              You can simply do this:



                              System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);





                              share|improve this answer






























                                2














                                If one really want to resize an array you could do something like this:



                                String[] arr = "a", "b", "c";
                                System.out.println(Arrays.toString(arr));
                                // Output is: [a, b, c]

                                arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
                                arr[3] = "d";
                                arr[4] = "e";
                                arr[5] = "f";

                                System.out.println(Arrays.toString(arr));
                                // Output is: [a, b, c, d, e, f, null, null, null, null]





                                share|improve this answer






























                                  1














                                  Size of array cannot be modified. If you have to use an array, you can use System.arraycopy(src, srcpos, dest, destpos, length);






                                  share|improve this answer





















                                    protected by Community Jul 12 '15 at 5:26



                                    Thank you for your interest in this question.
                                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                    Would you like to answer one of these unanswered questions instead?














                                    17 Answers
                                    17






                                    active

                                    oldest

                                    votes








                                    17 Answers
                                    17






                                    active

                                    oldest

                                    votes









                                    active

                                    oldest

                                    votes






                                    active

                                    oldest

                                    votes









                                    357














                                    The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.



                                    A better solution would be to use an ArrayList which can grow as you need it. The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.



                                    List<String> where = new ArrayList<String>();
                                    where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
                                    where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );


                                    If you need to convert it to a simple array...



                                    String[] simpleArray = new String[ where.size() ];
                                    where.toArray( simpleArray );


                                    But most things you do with an array you can do with this ArrayList, too:



                                    // iterate over the array
                                    for( String oneItem : where )
                                    ...


                                    // get specific items
                                    where.get( 1 );





                                    share|improve this answer




















                                    • 7





                                      What's the point in using Array if you can do the same with ArrayList?

                                      – Skoua
                                      Jan 11 '17 at 15:44






                                    • 5





                                      @Skoua speed!!!

                                      – vishalknishad
                                      Sep 22 '17 at 6:37











                                    • @tangens.I am new to android but your answer helped me.before finding answer i wasted many hours

                                      – vision
                                      Aug 27 '18 at 15:42















                                    357














                                    The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.



                                    A better solution would be to use an ArrayList which can grow as you need it. The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.



                                    List<String> where = new ArrayList<String>();
                                    where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
                                    where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );


                                    If you need to convert it to a simple array...



                                    String[] simpleArray = new String[ where.size() ];
                                    where.toArray( simpleArray );


                                    But most things you do with an array you can do with this ArrayList, too:



                                    // iterate over the array
                                    for( String oneItem : where )
                                    ...


                                    // get specific items
                                    where.get( 1 );





                                    share|improve this answer




















                                    • 7





                                      What's the point in using Array if you can do the same with ArrayList?

                                      – Skoua
                                      Jan 11 '17 at 15:44






                                    • 5





                                      @Skoua speed!!!

                                      – vishalknishad
                                      Sep 22 '17 at 6:37











                                    • @tangens.I am new to android but your answer helped me.before finding answer i wasted many hours

                                      – vision
                                      Aug 27 '18 at 15:42













                                    357












                                    357








                                    357







                                    The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.



                                    A better solution would be to use an ArrayList which can grow as you need it. The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.



                                    List<String> where = new ArrayList<String>();
                                    where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
                                    where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );


                                    If you need to convert it to a simple array...



                                    String[] simpleArray = new String[ where.size() ];
                                    where.toArray( simpleArray );


                                    But most things you do with an array you can do with this ArrayList, too:



                                    // iterate over the array
                                    for( String oneItem : where )
                                    ...


                                    // get specific items
                                    where.get( 1 );





                                    share|improve this answer















                                    The size of an array can't be modified. If you want a bigger array you have to instantiate a new one.



                                    A better solution would be to use an ArrayList which can grow as you need it. The method ArrayList.toArray( T[] a ) gives you back your array if you need it in this form.



                                    List<String> where = new ArrayList<String>();
                                    where.add( ContactsContract.Contacts.HAS_PHONE_NUMBER+"=1" );
                                    where.add( ContactsContract.Contacts.IN_VISIBLE_GROUP+"=1" );


                                    If you need to convert it to a simple array...



                                    String[] simpleArray = new String[ where.size() ];
                                    where.toArray( simpleArray );


                                    But most things you do with an array you can do with this ArrayList, too:



                                    // iterate over the array
                                    for( String oneItem : where )
                                    ...


                                    // get specific items
                                    where.get( 1 );






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Feb 13 '13 at 5:26









                                    Paul Bellora

                                    46k15113164




                                    46k15113164










                                    answered May 16 '10 at 10:38









                                    tangenstangens

                                    30.5k14107129




                                    30.5k14107129







                                    • 7





                                      What's the point in using Array if you can do the same with ArrayList?

                                      – Skoua
                                      Jan 11 '17 at 15:44






                                    • 5





                                      @Skoua speed!!!

                                      – vishalknishad
                                      Sep 22 '17 at 6:37











                                    • @tangens.I am new to android but your answer helped me.before finding answer i wasted many hours

                                      – vision
                                      Aug 27 '18 at 15:42












                                    • 7





                                      What's the point in using Array if you can do the same with ArrayList?

                                      – Skoua
                                      Jan 11 '17 at 15:44






                                    • 5





                                      @Skoua speed!!!

                                      – vishalknishad
                                      Sep 22 '17 at 6:37











                                    • @tangens.I am new to android but your answer helped me.before finding answer i wasted many hours

                                      – vision
                                      Aug 27 '18 at 15:42







                                    7




                                    7





                                    What's the point in using Array if you can do the same with ArrayList?

                                    – Skoua
                                    Jan 11 '17 at 15:44





                                    What's the point in using Array if you can do the same with ArrayList?

                                    – Skoua
                                    Jan 11 '17 at 15:44




                                    5




                                    5





                                    @Skoua speed!!!

                                    – vishalknishad
                                    Sep 22 '17 at 6:37





                                    @Skoua speed!!!

                                    – vishalknishad
                                    Sep 22 '17 at 6:37













                                    @tangens.I am new to android but your answer helped me.before finding answer i wasted many hours

                                    – vision
                                    Aug 27 '18 at 15:42





                                    @tangens.I am new to android but your answer helped me.before finding answer i wasted many hours

                                    – vision
                                    Aug 27 '18 at 15:42













                                    92














                                    Use a List<String>, such as an ArrayList<String>. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).



                                    import java.util.*;
                                    //....

                                    List<String> list = new ArrayList<String>();
                                    list.add("1");
                                    list.add("2");
                                    list.add("3");
                                    System.out.println(list); // prints "[1, 2, 3]"


                                    If you insist on using arrays, you can use java.util.Arrays.copyOf to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.



                                    static <T> T[] append(T[] arr, T element) 
                                    final int N = arr.length;
                                    arr = Arrays.copyOf(arr, N + 1);
                                    arr[N] = element;
                                    return arr;


                                    String[] arr = "1", "2", "3" ;
                                    System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
                                    arr = append(arr, "4");
                                    System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"


                                    This is O(N) per append. ArrayList, on the other hand, has O(1) amortized cost per operation.



                                    See also




                                    • Java Tutorials/Arrays

                                      • An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.


                                    • Java Tutorials/The List interface





                                    share|improve this answer

























                                    • You can double the size of the array every time the capacity is not enough. That way append will be amortized O(1). Probably what ArrayList does internally.

                                      – Siyuan Ren
                                      Jan 24 '14 at 7:55















                                    92














                                    Use a List<String>, such as an ArrayList<String>. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).



                                    import java.util.*;
                                    //....

                                    List<String> list = new ArrayList<String>();
                                    list.add("1");
                                    list.add("2");
                                    list.add("3");
                                    System.out.println(list); // prints "[1, 2, 3]"


                                    If you insist on using arrays, you can use java.util.Arrays.copyOf to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.



                                    static <T> T[] append(T[] arr, T element) 
                                    final int N = arr.length;
                                    arr = Arrays.copyOf(arr, N + 1);
                                    arr[N] = element;
                                    return arr;


                                    String[] arr = "1", "2", "3" ;
                                    System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
                                    arr = append(arr, "4");
                                    System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"


                                    This is O(N) per append. ArrayList, on the other hand, has O(1) amortized cost per operation.



                                    See also




                                    • Java Tutorials/Arrays

                                      • An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.


                                    • Java Tutorials/The List interface





                                    share|improve this answer

























                                    • You can double the size of the array every time the capacity is not enough. That way append will be amortized O(1). Probably what ArrayList does internally.

                                      – Siyuan Ren
                                      Jan 24 '14 at 7:55













                                    92












                                    92








                                    92







                                    Use a List<String>, such as an ArrayList<String>. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).



                                    import java.util.*;
                                    //....

                                    List<String> list = new ArrayList<String>();
                                    list.add("1");
                                    list.add("2");
                                    list.add("3");
                                    System.out.println(list); // prints "[1, 2, 3]"


                                    If you insist on using arrays, you can use java.util.Arrays.copyOf to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.



                                    static <T> T[] append(T[] arr, T element) 
                                    final int N = arr.length;
                                    arr = Arrays.copyOf(arr, N + 1);
                                    arr[N] = element;
                                    return arr;


                                    String[] arr = "1", "2", "3" ;
                                    System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
                                    arr = append(arr, "4");
                                    System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"


                                    This is O(N) per append. ArrayList, on the other hand, has O(1) amortized cost per operation.



                                    See also




                                    • Java Tutorials/Arrays

                                      • An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.


                                    • Java Tutorials/The List interface





                                    share|improve this answer















                                    Use a List<String>, such as an ArrayList<String>. It's dynamically growable, unlike arrays (see: Effective Java 2nd Edition, Item 25: Prefer lists to arrays).



                                    import java.util.*;
                                    //....

                                    List<String> list = new ArrayList<String>();
                                    list.add("1");
                                    list.add("2");
                                    list.add("3");
                                    System.out.println(list); // prints "[1, 2, 3]"


                                    If you insist on using arrays, you can use java.util.Arrays.copyOf to allocate a bigger array to accomodate the additional element. This is really not the best solution, though.



                                    static <T> T[] append(T[] arr, T element) 
                                    final int N = arr.length;
                                    arr = Arrays.copyOf(arr, N + 1);
                                    arr[N] = element;
                                    return arr;


                                    String[] arr = "1", "2", "3" ;
                                    System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3]"
                                    arr = append(arr, "4");
                                    System.out.println(Arrays.toString(arr)); // prints "[1, 2, 3, 4]"


                                    This is O(N) per append. ArrayList, on the other hand, has O(1) amortized cost per operation.



                                    See also




                                    • Java Tutorials/Arrays

                                      • An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.


                                    • Java Tutorials/The List interface






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Feb 13 '13 at 5:24









                                    Paul Bellora

                                    46k15113164




                                    46k15113164










                                    answered May 16 '10 at 10:38









                                    polygenelubricantspolygenelubricants

                                    287k103513593




                                    287k103513593












                                    • You can double the size of the array every time the capacity is not enough. That way append will be amortized O(1). Probably what ArrayList does internally.

                                      – Siyuan Ren
                                      Jan 24 '14 at 7:55

















                                    • You can double the size of the array every time the capacity is not enough. That way append will be amortized O(1). Probably what ArrayList does internally.

                                      – Siyuan Ren
                                      Jan 24 '14 at 7:55
















                                    You can double the size of the array every time the capacity is not enough. That way append will be amortized O(1). Probably what ArrayList does internally.

                                    – Siyuan Ren
                                    Jan 24 '14 at 7:55





                                    You can double the size of the array every time the capacity is not enough. That way append will be amortized O(1). Probably what ArrayList does internally.

                                    – Siyuan Ren
                                    Jan 24 '14 at 7:55











                                    19














                                    There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.



                                    String[] array1 = new String[]"one", "two";
                                    String[] array2 = new String[]"three";
                                    String[] array = new String[array1.length + array2.length];
                                    System.arraycopy(array1, 0, array, 0, array1.length);
                                    System.arraycopy(array2, 0, array, array1.length, array2.length);





                                    share|improve this answer





























                                      19














                                      There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.



                                      String[] array1 = new String[]"one", "two";
                                      String[] array2 = new String[]"three";
                                      String[] array = new String[array1.length + array2.length];
                                      System.arraycopy(array1, 0, array, 0, array1.length);
                                      System.arraycopy(array2, 0, array, array1.length, array2.length);





                                      share|improve this answer



























                                        19












                                        19








                                        19







                                        There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.



                                        String[] array1 = new String[]"one", "two";
                                        String[] array2 = new String[]"three";
                                        String[] array = new String[array1.length + array2.length];
                                        System.arraycopy(array1, 0, array, 0, array1.length);
                                        System.arraycopy(array2, 0, array, array1.length, array2.length);





                                        share|improve this answer















                                        There is another option which i haven't seen here and which doesn't involve "complex" Objects or Collections.



                                        String[] array1 = new String[]"one", "two";
                                        String[] array2 = new String[]"three";
                                        String[] array = new String[array1.length + array2.length];
                                        System.arraycopy(array1, 0, array, 0, array1.length);
                                        System.arraycopy(array2, 0, array, array1.length, array2.length);






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Aug 21 '15 at 11:14

























                                        answered Aug 21 '15 at 11:06









                                        ACLimaACLima

                                        3581612




                                        3581612





















                                            17














                                            Apache Commons Lang has



                                            T[] t = ArrayUtils.add( initialArray, newitem );


                                            it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.






                                            share|improve this answer



























                                              17














                                              Apache Commons Lang has



                                              T[] t = ArrayUtils.add( initialArray, newitem );


                                              it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.






                                              share|improve this answer

























                                                17












                                                17








                                                17







                                                Apache Commons Lang has



                                                T[] t = ArrayUtils.add( initialArray, newitem );


                                                it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.






                                                share|improve this answer













                                                Apache Commons Lang has



                                                T[] t = ArrayUtils.add( initialArray, newitem );


                                                it returns a new array, but if you're really working with arrays for some reason, this may be the ideal way to do this.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Jul 27 '17 at 20:42









                                                xenoterracidexenoterracide

                                                7,429762152




                                                7,429762152





















                                                    12














                                                    There is no method append() on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.



                                                    List<String> where = new ArrayList<String>();
                                                    where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
                                                    where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


                                                    Or if you are really keen to use an array:



                                                    String[] where = new String[]
                                                    ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
                                                    ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
                                                    ;


                                                    but then this is a fixed size and no elements can be added.






                                                    share|improve this answer























                                                    • So does a parameterized query accept ArrayList as selectionArgs as well?

                                                      – Skynet
                                                      Oct 19 '15 at 14:19















                                                    12














                                                    There is no method append() on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.



                                                    List<String> where = new ArrayList<String>();
                                                    where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
                                                    where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


                                                    Or if you are really keen to use an array:



                                                    String[] where = new String[]
                                                    ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
                                                    ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
                                                    ;


                                                    but then this is a fixed size and no elements can be added.






                                                    share|improve this answer























                                                    • So does a parameterized query accept ArrayList as selectionArgs as well?

                                                      – Skynet
                                                      Oct 19 '15 at 14:19













                                                    12












                                                    12








                                                    12







                                                    There is no method append() on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.



                                                    List<String> where = new ArrayList<String>();
                                                    where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
                                                    where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


                                                    Or if you are really keen to use an array:



                                                    String[] where = new String[]
                                                    ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
                                                    ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
                                                    ;


                                                    but then this is a fixed size and no elements can be added.






                                                    share|improve this answer













                                                    There is no method append() on arrays. Instead as already suggested a List object can service the need for dynamically inserting elements eg.



                                                    List<String> where = new ArrayList<String>();
                                                    where.add(ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1");
                                                    where.add(ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1");


                                                    Or if you are really keen to use an array:



                                                    String[] where = new String[]
                                                    ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
                                                    ContactsContract.Contacts.IN_VISIBLE_GROUP + "=1"
                                                    ;


                                                    but then this is a fixed size and no elements can be added.







                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered May 16 '10 at 10:58









                                                    RobertRobert

                                                    5,32362954




                                                    5,32362954












                                                    • So does a parameterized query accept ArrayList as selectionArgs as well?

                                                      – Skynet
                                                      Oct 19 '15 at 14:19

















                                                    • So does a parameterized query accept ArrayList as selectionArgs as well?

                                                      – Skynet
                                                      Oct 19 '15 at 14:19
















                                                    So does a parameterized query accept ArrayList as selectionArgs as well?

                                                    – Skynet
                                                    Oct 19 '15 at 14:19





                                                    So does a parameterized query accept ArrayList as selectionArgs as well?

                                                    – Skynet
                                                    Oct 19 '15 at 14:19











                                                    7














                                                    String[] source = new String[] "a", "b", "c", "d" ;
                                                    String[] destination = new String[source.length + 2];
                                                    destination[0] = "/bin/sh";
                                                    destination[1] = "-c";
                                                    System.arraycopy(source, 0, destination, 2, source.length);

                                                    for (String parts : destination)
                                                    System.out.println(parts);






                                                    share|improve this answer



























                                                      7














                                                      String[] source = new String[] "a", "b", "c", "d" ;
                                                      String[] destination = new String[source.length + 2];
                                                      destination[0] = "/bin/sh";
                                                      destination[1] = "-c";
                                                      System.arraycopy(source, 0, destination, 2, source.length);

                                                      for (String parts : destination)
                                                      System.out.println(parts);






                                                      share|improve this answer

























                                                        7












                                                        7








                                                        7







                                                        String[] source = new String[] "a", "b", "c", "d" ;
                                                        String[] destination = new String[source.length + 2];
                                                        destination[0] = "/bin/sh";
                                                        destination[1] = "-c";
                                                        System.arraycopy(source, 0, destination, 2, source.length);

                                                        for (String parts : destination)
                                                        System.out.println(parts);






                                                        share|improve this answer













                                                        String[] source = new String[] "a", "b", "c", "d" ;
                                                        String[] destination = new String[source.length + 2];
                                                        destination[0] = "/bin/sh";
                                                        destination[1] = "-c";
                                                        System.arraycopy(source, 0, destination, 2, source.length);

                                                        for (String parts : destination)
                                                        System.out.println(parts);







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jun 8 '15 at 12:50









                                                        dforcedforce

                                                        85411229




                                                        85411229





















                                                            6














                                                            As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.



                                                            String[] where = new String[10];


                                                            This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a
                                                            dynamically growing collection, use the ArrayList.






                                                            share|improve this answer



























                                                              6














                                                              As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.



                                                              String[] where = new String[10];


                                                              This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a
                                                              dynamically growing collection, use the ArrayList.






                                                              share|improve this answer

























                                                                6












                                                                6








                                                                6







                                                                As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.



                                                                String[] where = new String[10];


                                                                This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a
                                                                dynamically growing collection, use the ArrayList.






                                                                share|improve this answer













                                                                As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.



                                                                String[] where = new String[10];


                                                                This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a
                                                                dynamically growing collection, use the ArrayList.







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered May 16 '10 at 10:40









                                                                SimonSimon

                                                                7,60143152




                                                                7,60143152





















                                                                    5














                                                                    You need to use a Collection List. You cannot re-dimension an array.






                                                                    share|improve this answer



























                                                                      5














                                                                      You need to use a Collection List. You cannot re-dimension an array.






                                                                      share|improve this answer

























                                                                        5












                                                                        5








                                                                        5







                                                                        You need to use a Collection List. You cannot re-dimension an array.






                                                                        share|improve this answer













                                                                        You need to use a Collection List. You cannot re-dimension an array.







                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered May 16 '10 at 10:41









                                                                        PaligulusPaligulus

                                                                        2981313




                                                                        2981313





















                                                                            4














                                                                            If you would like to store your data in simple array like this



                                                                            String[] where = new String[10];


                                                                            and you want to add some elements to it like numbers please us StringBuilder which is much more efficient than concatenating string.



                                                                            StringBuilder phoneNumber = new StringBuilder();
                                                                            phoneNumber.append("1");
                                                                            phoneNumber.append("2");
                                                                            where[0] = phoneNumber.toString();


                                                                            This is much better method to build your string and store it into your 'where' array.






                                                                            share|improve this answer



























                                                                              4














                                                                              If you would like to store your data in simple array like this



                                                                              String[] where = new String[10];


                                                                              and you want to add some elements to it like numbers please us StringBuilder which is much more efficient than concatenating string.



                                                                              StringBuilder phoneNumber = new StringBuilder();
                                                                              phoneNumber.append("1");
                                                                              phoneNumber.append("2");
                                                                              where[0] = phoneNumber.toString();


                                                                              This is much better method to build your string and store it into your 'where' array.






                                                                              share|improve this answer

























                                                                                4












                                                                                4








                                                                                4







                                                                                If you would like to store your data in simple array like this



                                                                                String[] where = new String[10];


                                                                                and you want to add some elements to it like numbers please us StringBuilder which is much more efficient than concatenating string.



                                                                                StringBuilder phoneNumber = new StringBuilder();
                                                                                phoneNumber.append("1");
                                                                                phoneNumber.append("2");
                                                                                where[0] = phoneNumber.toString();


                                                                                This is much better method to build your string and store it into your 'where' array.






                                                                                share|improve this answer













                                                                                If you would like to store your data in simple array like this



                                                                                String[] where = new String[10];


                                                                                and you want to add some elements to it like numbers please us StringBuilder which is much more efficient than concatenating string.



                                                                                StringBuilder phoneNumber = new StringBuilder();
                                                                                phoneNumber.append("1");
                                                                                phoneNumber.append("2");
                                                                                where[0] = phoneNumber.toString();


                                                                                This is much better method to build your string and store it into your 'where' array.







                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Jan 24 '14 at 12:48









                                                                                RMachnikRMachnik

                                                                                2,92512243




                                                                                2,92512243





















                                                                                    4














                                                                                    Adding new items to String array.



                                                                                    String[] myArray = new String[] "x", "y";

                                                                                    // Convert array to list
                                                                                    List<String> listFromArray = Arrays.asList(myArray);

                                                                                    // Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
                                                                                    List<String> tempList = new ArrayList<String>(listFromArray);
                                                                                    tempList.add("z");

                                                                                    //Convert list back to array
                                                                                    String[] tempArray = new String[tempList.size()];
                                                                                    myArray = tempList.toArray(tempArray);





                                                                                    share|improve this answer

























                                                                                    • Ah, I see, you used the <code> tag and this had problems with the generic types. Please try to avoid this tag, since ... it has problems, and indent your code with 4 whitespaces to get the proper formatting. I did that for your question :).

                                                                                      – Tom
                                                                                      Dec 11 '15 at 17:09















                                                                                    4














                                                                                    Adding new items to String array.



                                                                                    String[] myArray = new String[] "x", "y";

                                                                                    // Convert array to list
                                                                                    List<String> listFromArray = Arrays.asList(myArray);

                                                                                    // Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
                                                                                    List<String> tempList = new ArrayList<String>(listFromArray);
                                                                                    tempList.add("z");

                                                                                    //Convert list back to array
                                                                                    String[] tempArray = new String[tempList.size()];
                                                                                    myArray = tempList.toArray(tempArray);





                                                                                    share|improve this answer

























                                                                                    • Ah, I see, you used the <code> tag and this had problems with the generic types. Please try to avoid this tag, since ... it has problems, and indent your code with 4 whitespaces to get the proper formatting. I did that for your question :).

                                                                                      – Tom
                                                                                      Dec 11 '15 at 17:09













                                                                                    4












                                                                                    4








                                                                                    4







                                                                                    Adding new items to String array.



                                                                                    String[] myArray = new String[] "x", "y";

                                                                                    // Convert array to list
                                                                                    List<String> listFromArray = Arrays.asList(myArray);

                                                                                    // Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
                                                                                    List<String> tempList = new ArrayList<String>(listFromArray);
                                                                                    tempList.add("z");

                                                                                    //Convert list back to array
                                                                                    String[] tempArray = new String[tempList.size()];
                                                                                    myArray = tempList.toArray(tempArray);





                                                                                    share|improve this answer















                                                                                    Adding new items to String array.



                                                                                    String[] myArray = new String[] "x", "y";

                                                                                    // Convert array to list
                                                                                    List<String> listFromArray = Arrays.asList(myArray);

                                                                                    // Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
                                                                                    List<String> tempList = new ArrayList<String>(listFromArray);
                                                                                    tempList.add("z");

                                                                                    //Convert list back to array
                                                                                    String[] tempArray = new String[tempList.size()];
                                                                                    myArray = tempList.toArray(tempArray);






                                                                                    share|improve this answer














                                                                                    share|improve this answer



                                                                                    share|improve this answer








                                                                                    edited Dec 11 '15 at 17:08









                                                                                    Tom

                                                                                    9,817143643




                                                                                    9,817143643










                                                                                    answered Dec 11 '15 at 16:25









                                                                                    KrisKris

                                                                                    388316




                                                                                    388316












                                                                                    • Ah, I see, you used the <code> tag and this had problems with the generic types. Please try to avoid this tag, since ... it has problems, and indent your code with 4 whitespaces to get the proper formatting. I did that for your question :).

                                                                                      – Tom
                                                                                      Dec 11 '15 at 17:09

















                                                                                    • Ah, I see, you used the <code> tag and this had problems with the generic types. Please try to avoid this tag, since ... it has problems, and indent your code with 4 whitespaces to get the proper formatting. I did that for your question :).

                                                                                      – Tom
                                                                                      Dec 11 '15 at 17:09
















                                                                                    Ah, I see, you used the <code> tag and this had problems with the generic types. Please try to avoid this tag, since ... it has problems, and indent your code with 4 whitespaces to get the proper formatting. I did that for your question :).

                                                                                    – Tom
                                                                                    Dec 11 '15 at 17:09





                                                                                    Ah, I see, you used the <code> tag and this had problems with the generic types. Please try to avoid this tag, since ... it has problems, and indent your code with 4 whitespaces to get the proper formatting. I did that for your question :).

                                                                                    – Tom
                                                                                    Dec 11 '15 at 17:09











                                                                                    4














                                                                                    I've made this code! It works like a charm!



                                                                                    public String[] AddToStringArray(String[] oldArray, String newString)

                                                                                    String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
                                                                                    newArray[oldArray.length] = newString;
                                                                                    return newArray;



                                                                                    I hope you like it!!






                                                                                    share|improve this answer





























                                                                                      4














                                                                                      I've made this code! It works like a charm!



                                                                                      public String[] AddToStringArray(String[] oldArray, String newString)

                                                                                      String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
                                                                                      newArray[oldArray.length] = newString;
                                                                                      return newArray;



                                                                                      I hope you like it!!






                                                                                      share|improve this answer



























                                                                                        4












                                                                                        4








                                                                                        4







                                                                                        I've made this code! It works like a charm!



                                                                                        public String[] AddToStringArray(String[] oldArray, String newString)

                                                                                        String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
                                                                                        newArray[oldArray.length] = newString;
                                                                                        return newArray;



                                                                                        I hope you like it!!






                                                                                        share|improve this answer















                                                                                        I've made this code! It works like a charm!



                                                                                        public String[] AddToStringArray(String[] oldArray, String newString)

                                                                                        String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
                                                                                        newArray[oldArray.length] = newString;
                                                                                        return newArray;



                                                                                        I hope you like it!!







                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        edited Sep 9 '17 at 21:34

























                                                                                        answered Sep 9 '17 at 21:25









                                                                                        AngeLAngeL

                                                                                        16029




                                                                                        16029





















                                                                                            4














                                                                                            There are many ways to add an element to an array. You can use a temp List to manage the element and then convert it back to Array or you can use the java.util.Arrays.copyOf and combine it with generics for better results.



                                                                                            This example will show you how:



                                                                                            public static <T> T[] append2Array(T[] elements, T element)

                                                                                            T[] newArray = Arrays.copyOf(elements, elements.length + 1);
                                                                                            newArray[elements.length] = element;

                                                                                            return newArray;



                                                                                            To use this method you just need to call it like this:



                                                                                            String[] numbers = new String[]"one", "two", "three";
                                                                                            System.out.println(Arrays.toString(numbers));
                                                                                            numbers = append2Array(numbers, "four");
                                                                                            System.out.println(Arrays.toString(numbers));


                                                                                            If you want to merge two array you can modify the previous method like this:



                                                                                            public static <T> T[] append2Array(T[] elements, T[] newElements)

                                                                                            T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
                                                                                            System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);

                                                                                            return newArray;



                                                                                            Now you can call the method like this:



                                                                                            String[] numbers = new String[]"one", "two", "three";
                                                                                            String[] moreNumbers = new String[]"four", "five", "six";
                                                                                            System.out.println(Arrays.toString(numbers));
                                                                                            numbers = append2Array(numbers, moreNumbers);
                                                                                            System.out.println(Arrays.toString(numbers));


                                                                                            As I mentioned, you also may use List objects. However, it will require a little hack to cast it safe like this:



                                                                                            public static <T> T[] append2Array(Class<T[]> clazz, List<T> elements, T element)

                                                                                            elements.add(element);
                                                                                            return clazz.cast(elements.toArray());



                                                                                            Now you can call the method like this:



                                                                                            String[] numbers = new String[]"one", "two", "three";
                                                                                            System.out.println(Arrays.toString(numbers));
                                                                                            numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
                                                                                            System.out.println(Arrays.toString(numbers));





                                                                                            share|improve this answer





























                                                                                              4














                                                                                              There are many ways to add an element to an array. You can use a temp List to manage the element and then convert it back to Array or you can use the java.util.Arrays.copyOf and combine it with generics for better results.



                                                                                              This example will show you how:



                                                                                              public static <T> T[] append2Array(T[] elements, T element)

                                                                                              T[] newArray = Arrays.copyOf(elements, elements.length + 1);
                                                                                              newArray[elements.length] = element;

                                                                                              return newArray;



                                                                                              To use this method you just need to call it like this:



                                                                                              String[] numbers = new String[]"one", "two", "three";
                                                                                              System.out.println(Arrays.toString(numbers));
                                                                                              numbers = append2Array(numbers, "four");
                                                                                              System.out.println(Arrays.toString(numbers));


                                                                                              If you want to merge two array you can modify the previous method like this:



                                                                                              public static <T> T[] append2Array(T[] elements, T[] newElements)

                                                                                              T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
                                                                                              System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);

                                                                                              return newArray;



                                                                                              Now you can call the method like this:



                                                                                              String[] numbers = new String[]"one", "two", "three";
                                                                                              String[] moreNumbers = new String[]"four", "five", "six";
                                                                                              System.out.println(Arrays.toString(numbers));
                                                                                              numbers = append2Array(numbers, moreNumbers);
                                                                                              System.out.println(Arrays.toString(numbers));


                                                                                              As I mentioned, you also may use List objects. However, it will require a little hack to cast it safe like this:



                                                                                              public static <T> T[] append2Array(Class<T[]> clazz, List<T> elements, T element)

                                                                                              elements.add(element);
                                                                                              return clazz.cast(elements.toArray());



                                                                                              Now you can call the method like this:



                                                                                              String[] numbers = new String[]"one", "two", "three";
                                                                                              System.out.println(Arrays.toString(numbers));
                                                                                              numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
                                                                                              System.out.println(Arrays.toString(numbers));





                                                                                              share|improve this answer



























                                                                                                4












                                                                                                4








                                                                                                4







                                                                                                There are many ways to add an element to an array. You can use a temp List to manage the element and then convert it back to Array or you can use the java.util.Arrays.copyOf and combine it with generics for better results.



                                                                                                This example will show you how:



                                                                                                public static <T> T[] append2Array(T[] elements, T element)

                                                                                                T[] newArray = Arrays.copyOf(elements, elements.length + 1);
                                                                                                newArray[elements.length] = element;

                                                                                                return newArray;



                                                                                                To use this method you just need to call it like this:



                                                                                                String[] numbers = new String[]"one", "two", "three";
                                                                                                System.out.println(Arrays.toString(numbers));
                                                                                                numbers = append2Array(numbers, "four");
                                                                                                System.out.println(Arrays.toString(numbers));


                                                                                                If you want to merge two array you can modify the previous method like this:



                                                                                                public static <T> T[] append2Array(T[] elements, T[] newElements)

                                                                                                T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
                                                                                                System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);

                                                                                                return newArray;



                                                                                                Now you can call the method like this:



                                                                                                String[] numbers = new String[]"one", "two", "three";
                                                                                                String[] moreNumbers = new String[]"four", "five", "six";
                                                                                                System.out.println(Arrays.toString(numbers));
                                                                                                numbers = append2Array(numbers, moreNumbers);
                                                                                                System.out.println(Arrays.toString(numbers));


                                                                                                As I mentioned, you also may use List objects. However, it will require a little hack to cast it safe like this:



                                                                                                public static <T> T[] append2Array(Class<T[]> clazz, List<T> elements, T element)

                                                                                                elements.add(element);
                                                                                                return clazz.cast(elements.toArray());



                                                                                                Now you can call the method like this:



                                                                                                String[] numbers = new String[]"one", "two", "three";
                                                                                                System.out.println(Arrays.toString(numbers));
                                                                                                numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
                                                                                                System.out.println(Arrays.toString(numbers));





                                                                                                share|improve this answer















                                                                                                There are many ways to add an element to an array. You can use a temp List to manage the element and then convert it back to Array or you can use the java.util.Arrays.copyOf and combine it with generics for better results.



                                                                                                This example will show you how:



                                                                                                public static <T> T[] append2Array(T[] elements, T element)

                                                                                                T[] newArray = Arrays.copyOf(elements, elements.length + 1);
                                                                                                newArray[elements.length] = element;

                                                                                                return newArray;



                                                                                                To use this method you just need to call it like this:



                                                                                                String[] numbers = new String[]"one", "two", "three";
                                                                                                System.out.println(Arrays.toString(numbers));
                                                                                                numbers = append2Array(numbers, "four");
                                                                                                System.out.println(Arrays.toString(numbers));


                                                                                                If you want to merge two array you can modify the previous method like this:



                                                                                                public static <T> T[] append2Array(T[] elements, T[] newElements)

                                                                                                T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
                                                                                                System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);

                                                                                                return newArray;



                                                                                                Now you can call the method like this:



                                                                                                String[] numbers = new String[]"one", "two", "three";
                                                                                                String[] moreNumbers = new String[]"four", "five", "six";
                                                                                                System.out.println(Arrays.toString(numbers));
                                                                                                numbers = append2Array(numbers, moreNumbers);
                                                                                                System.out.println(Arrays.toString(numbers));


                                                                                                As I mentioned, you also may use List objects. However, it will require a little hack to cast it safe like this:



                                                                                                public static <T> T[] append2Array(Class<T[]> clazz, List<T> elements, T element)

                                                                                                elements.add(element);
                                                                                                return clazz.cast(elements.toArray());



                                                                                                Now you can call the method like this:



                                                                                                String[] numbers = new String[]"one", "two", "three";
                                                                                                System.out.println(Arrays.toString(numbers));
                                                                                                numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
                                                                                                System.out.println(Arrays.toString(numbers));






                                                                                                share|improve this answer














                                                                                                share|improve this answer



                                                                                                share|improve this answer








                                                                                                edited Jan 8 at 13:47

























                                                                                                answered Sep 21 '18 at 7:36









                                                                                                TeocciTeocci

                                                                                                1,97711324




                                                                                                1,97711324





















                                                                                                    3














                                                                                                    I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size.
                                                                                                    You have to use an ArrayList or a Vector or any other dynamic structure.






                                                                                                    share|improve this answer



























                                                                                                      3














                                                                                                      I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size.
                                                                                                      You have to use an ArrayList or a Vector or any other dynamic structure.






                                                                                                      share|improve this answer

























                                                                                                        3












                                                                                                        3








                                                                                                        3







                                                                                                        I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size.
                                                                                                        You have to use an ArrayList or a Vector or any other dynamic structure.






                                                                                                        share|improve this answer













                                                                                                        I'm not that experienced in Java but I have always been told that arrays are static structures that have a predefined size.
                                                                                                        You have to use an ArrayList or a Vector or any other dynamic structure.







                                                                                                        share|improve this answer












                                                                                                        share|improve this answer



                                                                                                        share|improve this answer










                                                                                                        answered May 16 '10 at 10:41









                                                                                                        npintinpinti

                                                                                                        46.7k55884




                                                                                                        46.7k55884





















                                                                                                            2














                                                                                                            you can create a arraylist, and use Collection.addAll() to convert the string array to your arraylist






                                                                                                            share|improve this answer



























                                                                                                              2














                                                                                                              you can create a arraylist, and use Collection.addAll() to convert the string array to your arraylist






                                                                                                              share|improve this answer

























                                                                                                                2












                                                                                                                2








                                                                                                                2







                                                                                                                you can create a arraylist, and use Collection.addAll() to convert the string array to your arraylist






                                                                                                                share|improve this answer













                                                                                                                you can create a arraylist, and use Collection.addAll() to convert the string array to your arraylist







                                                                                                                share|improve this answer












                                                                                                                share|improve this answer



                                                                                                                share|improve this answer










                                                                                                                answered Feb 3 '14 at 13:43









                                                                                                                ratzipratzip

                                                                                                                508




                                                                                                                508





















                                                                                                                    2














                                                                                                                    You can simply do this:



                                                                                                                    System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);





                                                                                                                    share|improve this answer



























                                                                                                                      2














                                                                                                                      You can simply do this:



                                                                                                                      System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);





                                                                                                                      share|improve this answer

























                                                                                                                        2












                                                                                                                        2








                                                                                                                        2







                                                                                                                        You can simply do this:



                                                                                                                        System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);





                                                                                                                        share|improve this answer













                                                                                                                        You can simply do this:



                                                                                                                        System.arraycopy(initialArray, 0, newArray, 0, initialArray.length);






                                                                                                                        share|improve this answer












                                                                                                                        share|improve this answer



                                                                                                                        share|improve this answer










                                                                                                                        answered Feb 2 '17 at 9:19









                                                                                                                        Jason IveyJason Ivey

                                                                                                                        157114




                                                                                                                        157114





















                                                                                                                            2














                                                                                                                            If one really want to resize an array you could do something like this:



                                                                                                                            String[] arr = "a", "b", "c";
                                                                                                                            System.out.println(Arrays.toString(arr));
                                                                                                                            // Output is: [a, b, c]

                                                                                                                            arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
                                                                                                                            arr[3] = "d";
                                                                                                                            arr[4] = "e";
                                                                                                                            arr[5] = "f";

                                                                                                                            System.out.println(Arrays.toString(arr));
                                                                                                                            // Output is: [a, b, c, d, e, f, null, null, null, null]





                                                                                                                            share|improve this answer



























                                                                                                                              2














                                                                                                                              If one really want to resize an array you could do something like this:



                                                                                                                              String[] arr = "a", "b", "c";
                                                                                                                              System.out.println(Arrays.toString(arr));
                                                                                                                              // Output is: [a, b, c]

                                                                                                                              arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
                                                                                                                              arr[3] = "d";
                                                                                                                              arr[4] = "e";
                                                                                                                              arr[5] = "f";

                                                                                                                              System.out.println(Arrays.toString(arr));
                                                                                                                              // Output is: [a, b, c, d, e, f, null, null, null, null]





                                                                                                                              share|improve this answer

























                                                                                                                                2












                                                                                                                                2








                                                                                                                                2







                                                                                                                                If one really want to resize an array you could do something like this:



                                                                                                                                String[] arr = "a", "b", "c";
                                                                                                                                System.out.println(Arrays.toString(arr));
                                                                                                                                // Output is: [a, b, c]

                                                                                                                                arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
                                                                                                                                arr[3] = "d";
                                                                                                                                arr[4] = "e";
                                                                                                                                arr[5] = "f";

                                                                                                                                System.out.println(Arrays.toString(arr));
                                                                                                                                // Output is: [a, b, c, d, e, f, null, null, null, null]





                                                                                                                                share|improve this answer













                                                                                                                                If one really want to resize an array you could do something like this:



                                                                                                                                String[] arr = "a", "b", "c";
                                                                                                                                System.out.println(Arrays.toString(arr));
                                                                                                                                // Output is: [a, b, c]

                                                                                                                                arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
                                                                                                                                arr[3] = "d";
                                                                                                                                arr[4] = "e";
                                                                                                                                arr[5] = "f";

                                                                                                                                System.out.println(Arrays.toString(arr));
                                                                                                                                // Output is: [a, b, c, d, e, f, null, null, null, null]






                                                                                                                                share|improve this answer












                                                                                                                                share|improve this answer



                                                                                                                                share|improve this answer










                                                                                                                                answered Nov 12 '17 at 22:33









                                                                                                                                Baked InhalfBaked Inhalf

                                                                                                                                1,0391227




                                                                                                                                1,0391227





















                                                                                                                                    1














                                                                                                                                    Size of array cannot be modified. If you have to use an array, you can use System.arraycopy(src, srcpos, dest, destpos, length);






                                                                                                                                    share|improve this answer



























                                                                                                                                      1














                                                                                                                                      Size of array cannot be modified. If you have to use an array, you can use System.arraycopy(src, srcpos, dest, destpos, length);






                                                                                                                                      share|improve this answer

























                                                                                                                                        1












                                                                                                                                        1








                                                                                                                                        1







                                                                                                                                        Size of array cannot be modified. If you have to use an array, you can use System.arraycopy(src, srcpos, dest, destpos, length);






                                                                                                                                        share|improve this answer













                                                                                                                                        Size of array cannot be modified. If you have to use an array, you can use System.arraycopy(src, srcpos, dest, destpos, length);







                                                                                                                                        share|improve this answer












                                                                                                                                        share|improve this answer



                                                                                                                                        share|improve this answer










                                                                                                                                        answered Sep 25 '14 at 4:36









                                                                                                                                        JiaoJiao

                                                                                                                                        335




                                                                                                                                        335















                                                                                                                                            protected by Community Jul 12 '15 at 5:26



                                                                                                                                            Thank you for your interest in this question.
                                                                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                                                                            Popular posts from this blog

                                                                                                                                            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                                                                                                                                            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                                                                                                                                            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme