TreeSet实例

TreeSet实例importjava.util.*;/***@descTreeSet的API测试**@authorChenny*/publicclassTreeSetTest{publicstaticvoidmain(String[]args){testTreeSetAPIs();}//测试TreeSe…

import java.util.*;

/** * @desc TreeSet的API测试 * * @author Chenny * / public class TreeSetTest { public static void main(String[] args) { testTreeSetAPIs(); } // 测试TreeSet的api public static void testTreeSetAPIs() { String val; // 新建TreeSet TreeSet tSet = new TreeSet(); // 将元素添加到TreeSet中 tSet.add("aaa"); // Set中不允许重复元素,所以只会保存一个“aaa” tSet.add("aaa"); tSet.add("bbb"); tSet.add("eee"); tSet.add("ddd"); tSet.add("ccc"); System.out.println("TreeSet:"+tSet); // 打印TreeSet的实际大小 System.out.printf("size : %d\n", tSet.size()); // 导航方法 // floor(小于、等于) System.out.printf("floor bbb: %s\n", tSet.floor("bbb")); // lower(小于) System.out.printf("lower bbb: %s\n", tSet.lower("bbb")); // ceiling(大于、等于) System.out.printf("ceiling bbb: %s\n", tSet.ceiling("bbb")); System.out.printf("ceiling eee: %s\n", tSet.ceiling("eee")); // ceiling(大于) System.out.printf("higher bbb: %s\n", tSet.higher("bbb")); // subSet() System.out.printf("subSet(aaa, true, ccc, true): %s\n", tSet.subSet("aaa", true, "ccc", true)); System.out.printf("subSet(aaa, true, ccc, false): %s\n", tSet.subSet("aaa", true, "ccc", false)); System.out.printf("subSet(aaa, false, ccc, true): %s\n", tSet.subSet("aaa", false, "ccc", true)); System.out.printf("subSet(aaa, false, ccc, false): %s\n", tSet.subSet("aaa", false, "ccc", false)); // headSet() System.out.printf("headSet(ccc, true): %s\n", tSet.headSet("ccc", true)); System.out.printf("headSet(ccc, false): %s\n", tSet.headSet("ccc", false)); // tailSet() System.out.printf("tailSet(ccc, true): %s\n", tSet.tailSet("ccc", true)); System.out.printf("tailSet(ccc, false): %s\n", tSet.tailSet("ccc", false)); // 删除“ccc” tSet.remove("ccc"); // 将Set转换为数组 String[] arr = (String[])tSet.toArray(new String[0]); for (String str:arr) System.out.printf("for each : %s\n", str); // 打印TreeSet System.out.printf("TreeSet:%s\n", tSet); // 遍历TreeSet for(Iterator iter = tSet.iterator(); iter.hasNext(); ) { System.out.printf("iter : %s\n", iter.next()); } // 删除并返回第一个元素 val = (String)tSet.pollFirst(); System.out.printf("pollFirst=%s, set=%s\n", val, tSet); // 删除并返回最后一个元素 val = (String)tSet.pollLast(); System.out.printf("pollLast=%s, set=%s\n", val, tSet); // 清空HashSet tSet.clear(); // 输出HashSet是否为空 System.out.printf("%s\n", tSet.isEmpty()?"set is empty":"set is not empty"); } } 

返回TreeSet常用方法

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/35163.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注