在Java中获取TreeSet的大小
要获取TreeSet的大小,请使用size()
方法。
创建一个TreeSet并向其中添加元素-
TreeSet<String> tSet = new TreeSet<String>(); tSet.add("78"); tSet.add("56"); tSet.add("88"); tSet.add("12");
现在,获取TreeSet的大小-
tSet.size()
以下是获取Java中TreeSet大小的示例-
示例
import java.util.*; public class Demo { public static void main(String args[]){ TreeSet<String> tSet = new TreeSet<String>(); tSet.add("78"); tSet.add("56"); tSet.add("88"); tSet.add("12"); System.out.println("TreeSet elements..."); Iterator<String> i = tSet.iterator(); while(i.hasNext()){ System.out.println(i.next()); } System.out.println("Size of TreeSet = " + tSet.size()); System.out.println("Removing Highest Value = "+tSet.pollLast()); System.out.println("\nUpdated TreeSet elements..."); i = tSet.iterator(); while(i.hasNext()){ System.out.println(i.next()); } System.out.println("Size of TreeSet after removing an element = " + tSet.size()); } }
输出结果
TreeSet elements... 12 56 78 88 Size of TreeSet = 4 Removing Highest Value = 88 Updated TreeSet elements... 12 56 78 Size of TreeSet after removing an element = 3