Can you change the length of an ArrayList?

trimToSize() method is used for memory optimization. It trims the capacity of ArrayList to the current list size. For e.g. An arraylist is having capacity of 15 but there are only 5 elements in it, calling trimToSize() method on this ArrayList would change the capacity from 15 to 5.

public void trimToSize()

Example

Here I have defined the ArrayList of capacity 50. After adding 10 elements I called trimToSize() method which would have reduced the capacity from 50 to 10 (current size of arraylist).

package beginnersbook.com; import java.util.ArrayList; public class TrimExample { public static void main(String args[]) { ArrayList arraylist = new ArrayList(50); arraylist.add(1); arraylist.add(2); arraylist.add(3); arraylist.add(4); arraylist.add(5); arraylist.add(6); arraylist.add(7); arraylist.add(1); arraylist.add(1); arraylist.add(1); arraylist.trimToSize(); System.out.println(arraylist); } }

Output:

[1, 2, 3, 4, 5, 6, 7, 1, 1, 1]

You can use the set() method of java.util.ArrayList class to replace an existing element of ArrayList in Java. The set(int index, E element) method takes two parameters, the first is the index of an element you want to replace, and the second is the new value you want to insert. You can use this method as long as your ArrayList is not immutable, I mean,  not created using the Collections.unmodifiableList(), in such case the set() method throws java.lang.UnsupportedOperationExcepiton

Though you can also use the set() method with the List returned by Arrays.asList() method as oppose to add() and remove() which is not supported there. You just need to be careful with the index of elements. For example, if you want to replace the first element then you need to call set(0, newValue) because similar to an array, the ArrayList index is also zero-based.

Now, the questions come why do you want to replace an element in the ArrayList? Why not just remove the element and insert a new one? Well, obviously the remove and insert will take more time than replace. 

The java.util.ArrayList provides O(1) time performance for replacement, similar to size(), isEmpty(), get()iterator(), and listIterator() operations which runs in constant time.

Now, you may wonder that why set() gives O(1) performance but add() gives O(n) performance, because it could trigger resizing of the array, which involves creating a new array and copying elements from the old array to the new array.  You can also see these free Java courses to learn more about the implementation and working of ArrayList in Java.

Here is an example of replacing an existing value from ArrayList in Java. In this example, I have an ArrayList of String which contains names of some of the most popular and useful books for Java programmers. 

Our example replaces the 2nd element of the ArrayList by calling the ArrayList.set(1, "Introduction to Algorithms") because the index of the array starts from zero. You should read a comprehensive course like The Complete Java Masterclass on Udemy to learn more about useful collection classes in Java, including ArrayList.

Can you change the length of an ArrayList?

import java.util.ArrayList; import java.util.List; /* * Java Program to demonstrate how to replace existing value in * ArrayList. */ public class ArrayListSetDemo { public static void main(String[] args) { // let's create a list first List<String> top5Books = new ArrayList<String>(); top5Books.add("Clean Code"); top5Books.add("Clean Coder"); top5Books.add("Effective Java"); top5Books.add("Head First Java"); top5Books.add("Head First Design patterns"); // now, suppose you want to replace "Clean Coder" with // "Introduction to Algorithms" System.out.println("ArrayList before replace: " + top5Books); top5Books.set(1, "Introductoin to Algorithms"); System.out.println("ArrayList after replace: " + top5Books); } } Output ArrayList before replace: [Clean Code, Clean Coder, Effective Java, Head First Java, Head First Design patterns] ArrayList after replace: [Clean Code, Introduction to Algorithms, Effective Java, Head First Java, Head First Design patterns]
You can see that initially, we have a list of 5 books and we have replaced the second element by calling the set(1, value) method, hence in the output, the second book which was "Clean Coder" was replaced by "Introduction to Algorithms".

That's all about how to replace existing elements of ArrayList in Java. The set() method is perfect to replace existing values just make sure that the List you are using is not immutable. You can also use this method with any other List type like LinkedList. The time complexity is O(n) because we are doing index-based access to the element.

Other ArrayList tutorials for Java Programmers


  • How to reverse an ArrayList in Java? (example)
  • How to loop through an ArrayList in Java? (tutorial)
  • How to synchronize an ArrayList in Java? (read)
  • How to create and initialize ArrayList in the same line? (example)
  • Difference between an Array and ArrayList in Java? (answer)
  • When to use ArrayList over LinkedList in Java? (answer)
  • Difference between ArrayList and Vector in Java? (answer)
  • How to get a sublist from ArrayList in Java? (example)
  • How to remove duplicate elements from ArrayList in Java? (tutorial)
  • How to sort an ArrayList in descending order in Java? (read)
  • Difference between ArrayList and HashSet in Java? (answer)
  • Difference between ArrayList and HashMap in Java? (answer)
Thanks for reading this tutorial so far. If you like this ArrayList replace example then please share it with your friends and colleagues. If you have any questions or feedback, please drop a note. 


You can use the size() method of java.util.ArrayList to find the length or size of ArrayList in Java. The size() method returns an integer equal to a number of elements present in the array list. It's different than the length of the array which is backing the ArrayList, which is called the capacity of ArrayList. When you create an object of ArrayList in Java without specifying a capacity, it is created with a default capacity which is 10. Since ArrayList is a growable array, it automatically resizes when the size (number of elements in the array list) grows beyond a threshold. 

Also, when an ArrayList is first created it is called empty ArrayList, and size() will return zero. If you add elements then size grows one by one. You can also remove all elements from ArrayList by using a clear() method which will then again make the ArrayList empty as shown in our examples. Here is our sample Java program to demonstrate how to find the length or size of ArrayList in Java. As discussed it uses the size() method to return a number of elements in the array list but it is different than capacity which is equal to the length of the underlying array and always greater than the size. The capacity is not publically exposed, as elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has a constant amortized time cost.

You can also use the trimToSize() method to trim the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance. See Core Java Volume 1 - Fundamentals book, or these free Java courses to learn more about essential collection classes and how they work.

Can you change the length of an ArrayList?

Java Program to find number of elements in ArrayList


import java.util.ArrayList; /* * Java Program to find the length of ArrayList. * */ public class ArrayListDemo{ public static void main(String[] args) { System.out.println("Welcome to Java Program to find the length of array list"); ArrayList<String> listOfBanks = new ArrayList<>(); int size = listOfBanks.size(); System.out.println("size of array list after creating: " + size); listOfBanks.add("Citibank"); listOfBanks.add("Chase"); listOfBanks.add("Bank of America"); size = listOfBanks.size(); System.out.println("length of ArrayList after adding elements: " + size); listOfBanks.clear(); size = listOfBanks.size(); System.out.println("size of ArrayList after clearing elements: " + size); } } Output Welcome to Java Program to find length of array list the size of array list after creating: 0 the length of ArrayList after adding elements: 3 the length of ArrayList after clearing elements: 0

From the above example, you can see that the initial size of ArrayList was zero, which increased to 3 after adding 3 elements and it finally becomes zero when you called the clear() method on the ArrayList object. This method removes all elements from the array list making it empty again so that you can reuse it.

Other Java ArrayList tutorials for Programmers


  • How to reverse an ArrayList in Java? (solution)
  • How to create and initialize the ArrayList in one line? (answer)
  • How to declare ArrayList with values in Java? (example)
  • How to convert an ArrayList to String in Java? (example)
  • How to remove duplicates from ArrayList in Java? (example)
  • How convert ArrayList to HashSet in Java? (example)
  • How to get the first and last element of ArrayList in Java? (solution)
  • How to loop over ArrayList in Java? (answer)
  • How to get a range of elements as sublists from ArrayList in Java? (example)
  • How to sort an ArrayList in Java? (answer)
  • How to remove all elements of ArrayList in Java? (answer)
  • How to remove a given element from ArrayList in Java? (answer)