枚举集 EnumSet类
Java EnumSet 类是用于枚举类型的专用 Set 实现。
它继承了 AbstractSet 类并实现了 Set 接口。
枚举集(EnumSet)示例
import java.util.*; enum days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } public class EnumSetExample { public static void main(String[] args) { Set set = EnumSet.of(days.TUESDAY, days.WEDNESDAY); //Traversing elements Iterator iter = set.iterator(); while (iter.hasNext()) System.out.println(iter.next()); } }
以数字开头的枚举
Java 不允许枚举的名称以数字开头,如 100A、25K。
在这种情况下,我们可以用 _(下划线)或者任何允许的模式添加代码并进行检查。
以名称开头的枚举
public enum BookCode { 10A("Simon Haykin", "Communication System"), _42B("Stefan Hakins", "A Brief History of Time"), E1("Sedra Smith", "Electronics Circuits"); private String author; private String title; BookCode(String author, String title) { this.author = author; this.title = title; } public String getName() { String name = name(); if (name.charAt(0) == '') { name = name.substring(1, name.length()); } return name; } public static BookCode of(String code) { if (Character.isDoirt(code.charAt(0))) { code = "_" + code; } return BookCode.valueOf(code); } }
哈希表 Hashtable
Hashtable 是 Java 集合中的一个类,它实现了 Map 接口并扩展了 Dictionary 类
仅包含唯一元素及其同步
import java.util.*; public class HashtableDemo { public static void main(String args[]) { //create and populate hash table Hashtable map = new Hashtable(); map.put(101,"C Language"); map.put(102, "Domain"); map.put(104, "Databases"); System.out.println("Values before remove: "+ map); //Remove value for key 102 map.remove(102); System.out.println("Values after remove: "+ map); } }
Java EnumMap示例
import java.util.*; class Book { int id; String name,author,publisher; int quantity; public Book(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; } } public class EnumMapExample { //Creating enum public enum Key{ One, Two, Three }; public static void main(String[] args) { EnumMap map = new EnumMap(Key.class); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to Map map.put(Key.One, b1); map.put(Key.Two, b2); map.put(Key.Three, b3); //Traversing EnumMap for(Map.Entry entry:map.entrySet()){ Book b=entry.getValue(); System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); } } }
Java EnumMap 类是枚举键的专用 Map 实现。
它继承了 Enum 和 AbstractMap 类。
java.util.EnumMap 类的参数。
K:就是这个map维护的key的类型。
V:它是映射值的类型。
日期:2020-06-02 22:15:17 来源:oir作者:oir