A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/java-tutorial/arraylist/arraylist_clear.php below:

Website Navigation


Java arraylist clear method - w3resource

Java ArrayList.clear() MethodLast update on August 19 2022 21:51:25 (UTC/GMT +8 hours) public void clear()

The clear() method is used to remove all of the elements from a list. The list will be empty after this call returns.

Package: java.util

Java Platform : Java SE 8

Syntax:

clear()

Return Value:
This method does not return any value.

Pictorial presentation of ArrayList.clear() Method

Example: ArrayList.clear() Method

The following example creates an ArrayList with a capacity of 7 elements. After adding some elements we have remove all the contents using clear(0 method.

import java.util.*;

public class test {
   public static void main(String[] args) {
      
    // create an empty array list with an initial capacity
    ArrayList<String> color_list = new ArrayList<String>(7);

    // use add() method to add values in the list
    color_list.add("White");
    color_list.add("Black");
    color_list.add("Red");
    color_list.add("White");
	color_list.add("Yellow");
	color_list.add("Red");
    color_list.add("White");
  
	// Print out the colors in the ArrayList
    System.out.println("****Color list****");
	for (int i = 0; i < 7; i++)
      {
         System.out.println(color_list.get(i).toString());
      }

    // Remove all the elements using clear()
    color_list.clear();
	
	//Now size of the list
	System.out.println("After using clear() method, the size of the list is: " + color_list.size()); 
	
	  }
}
   

Output:

F:\java>javac test.java

F:\java>java test
****Color list****
White
Black
Red
White
Yellow
Red
White
After using clear() method, the size of the list is: 0

Java Code Editor:

Previous:remove(Object o) Method
Next:addAll(Collection c) Method


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4