Java ArrayList trimToSize() Method
What is ArrayList in Java ?
Arraylist is a part of collection framework in java. It contains several inbuilt function like trimToSize()method which can be found in the java.util.ArrayList Package. It implements the List interface of the collections framework.
Java ArrayList trimToSize() Method :
The Java ArrayList class’s trimToSize() method reduces an instance’s capacity to match the list’s current size. Using this method, you can reduce the size of an ArrayList instance to the number of elements it has.Syntax :
public void trimToSize()
Parameters :
It does not take any parameter . we can simply use trimToSize() Method by using dot operator like
list.trimToSize()
Throws Exception :
It does throws any exceptions and error.
Return Value :
It provides no value in return. It reduces this ArrayList instance's capacity to the number of the elements it has.
Example 1 :
import java.util.*; public class Main { public static void main(String[] args) { //ArrayList object creation of size 8. ArrayList<String>list = new ArrayList<>(8); //Adding elements to the list list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add("F"); //Printing the initial list. System.out.println("ArrayList : " + list); //Trimming the list to size list.trimToSize(); //Printing the list after trimToSize() System.out.println("ArrayList after trimToSize() : " + list); } }
Output :
ArrayList : [A, B, C, D, E, F] ArrayList after trimToSize() : [A, B, C, D, E, F]
Explanation :
In the example above, we initially created an Array of size 8 and added only 6 values to it, leaving two extra spaces. We therefore used the trimToSize() method to remove the extra spaces in order to minimize this problem.
By this way we optimize the code with respect to space Complexity.
By this way we optimize the code with respect to space Complexity.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment