Core Java

Its very important to know the size of TreeSet as it is required in most of the times while coding

We have size() method in TreeSet class which helps us to determine the size of TreeSet

Size is the number of elements in that TreeSet

public int size()


Example :

  1. import java.util.*;
  2.  
  3. public class TreeSetSize {
  4.       public static void main(String[] args) {
  5.       TreeSet<Integer> ts = new TreeSet<Integer>();
  6.       ts.add(14);
  7.       ts.add(7);
  8.       ts.add(21);
  9.       ts.add(28);
  10.       ts.add(35);
  11.       ts.add(42);    
  12.       System.out.println("Initial Size of TreeSet: "+ts.size());
  13.       ts.remove(35);
  14.       ts.remove(42);
  15.       System.out.println("Size after removing 2 elements: "+ts.size());
  16.       System.out.println("Final TreeSet after removal of 2 elements: ");
  17.       for(int ele: ts){
  18.            System.out.println(ele);
  19.         }
  20.     }
  21. }
import java.util.*;

public class TreeSetSize {
      public static void main(String[] args) {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(14);
      ts.add(7);
      ts.add(21);
      ts.add(28);
      ts.add(35);
      ts.add(42);	 
      System.out.println("Initial Size of TreeSet: "+ts.size());
      ts.remove(35);
      ts.remove(42);
      System.out.println("Size after removing 2 elements: "+ts.size());
      System.out.println("Final TreeSet after removal of 2 elements: ");
      for(int ele: ts){
           System.out.println(ele);
        }
	}
}


Here Size just tells how many elements are present in the TreeSet

Don’t get confuse size with capacity in the TreeSet, we will talk about capacity separately

Just remember Size() returns number of elements present in TreeSet

Remember size() is a method , not a variable in the TreeSet class.

Share this article on

Comment (9)

    1. Karibasappa G C (KB)
      Karibasappa G C (KB)

      First thing, static variables will never be a part of method, it will be a part of class always.

      So only we cant declare any static variables inside a method but we can access them inside a method.

      All static variables will be stored in separate segment inside Heap area only.

      1. The blog is very helpful. Thanks a lot for sharing! Also the “Inheritance in interface” page is not opening. Can you please fix that?

Leave a Comment

  • You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" extra="">

    • Please answer this simple challenge to post your valuable comment *