How can I add new elements to an Array in Java

0 votes

I want to append elements to an array

String[] mm= {"5","4","3"};
mm.append("2");

This gives me a compile-time error

Please give me a way in which I can add elements to this array.

Apr 19, 2018 in Java by Parth
• 4,640 points
14,858 views

3 answers to this question.

0 votes

Java arrays are fixed in size. You cannot append elements in an array.

Instead, we can use an ArrayList object which implements the List interface.

An ArrayList can dynamically increase and decrease its size and thus it can append new elements to it for example :

List ll=new ArrayList("5","4","3");

ll.add("2");
answered Apr 19, 2018 by developer_1
• 3,350 points
ArrayList<String> myList = new ArrayList<String>(Arrays.adlist(myArray));

System.out.println("Enter elements to be added");

String element=sc.next();

myList.add(element);

myArray=myList.toArray(myList);

System.out.println(Arrays.toString(myArray));
0 votes

We can also add elements to the array without using complex objects and 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);
answered Jul 19, 2018 by Sushmita
• 6,920 points
0 votes
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);
}
answered Sep 19, 2018 by Sushmita
• 6,920 points

Related Questions In Java

0 votes
2 answers
0 votes
2 answers

How an object array can be converted to string array in java?

System.arraycopy is the most efficient way, but ...READ MORE

answered Aug 8, 2018 in Java <