ArrayList Java 9 how to add new item

There are two ways of adding new time to ArrayList in Java 9:

  • add() method with one parameter: element
  • add() method with two parameters: index and element
  • in case that you have only array than you can simulate adding of new element

ArrayList add new element

Add new element at the end of the ArrayList with add() method:

List<String> list = new ArrayList<String>();
list.add("Java 7");
list.add("Java 8");
list.add("Java 9");
System.out.println(list); // prints [Java 7, Java 8, Java 9]

result:

[Java 7, Java 8, Java 9]

ArrayList java add new element at position

If you want to add element to specific position than you can use parameter index:

List<String> mylist = Arrays.asList("Java 7", "Java 8", "Java 9");
mylist.add(0,"Java 6");
System.out.println(mylist); // prints [Java 6, Java 7, Java 8, Java 9]

result:

[Java 6, Java 7, Java 8, Java 9]

Array of strings add new item

Arrays are not dynamically able to grow as List and ArrayList and adding a new element should be done by simulation like:

String[] array1 = new String[]{"Java 7", "Java 8"};
String[] array2 = new String[]{"Java 9"};
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);
System.out.println(Arrays.toString(array)); // prints [Java 7, Java 8, Java 9]

result:

[Java 7, Java 8, Java 9]

Related Article