java的集合,泛型和枚举

414 阅读14分钟

集合

因为java的数组是不可以动态去增删的,所以java提供了集合类,集合里可以保存基本类型的值(集合里不能存放基础数据类型,如果要存储基础数据类型须要存储基础数据类型的包装类),也可以保存对象。

java的集合类型分为Collection类和Map类,它俩有衍生了很多子接口和类

 集合接口
   Iterator 遍历输出Collection集合中的元素
   Collection 是list Set和Queue的父接口,
   Queue  队列接口
   Dyeye  双向队列接口
   Kist  有序集合,允许有相同的元素
   Set  Js里的集合,不能包含重复的元素
   Map Js里的字典,以key-value保存数据


   实现类
    HashSet 基于HashMap实现的Set
    TreeSet 实现了Set接口,是一个有序的Set,可以从Set里提取一个有序序列
    ArrayList 用数组实现了List
    ArrayDueue  可以当称栈或者队列使用
    HashMap 用Hash算法存取键值对
    TreeMap对键值对进行排序

Collection

Collection接口是List ,Set,Queue的父接口,一般情况下不直接使用,Collection里定义了一些方法,可以直接对Set,List,Queue进行操作使用

 方法
 add    集合中添加元素
 addAll 添加一个集合
 clear  清除集合中的所有元素
 contains 判断集合中是否存在指定元素
 containsAll 判断集合中是否包含指定集合的所有元素
 isEmpty 判断集合是否为空
 Iterator 返回Iterator对象用于遍历集合中的元素
 remove 删除指定元素
 removeAll 删除指定集合中包含的所有元素
 retainAll 从集合里删除指定集合里不包含的元素
 size 返回元素的个数
 toArray 把集合转换为一个数组,所有的集合元素变成对应的数组元素  
import java.util.ArrayList;
import java.util.Iterator;

public class SetDemo {
    public static void  main(String [] args){
        ArrayList arrList1=new ArrayList();
        ArrayList arrList2=new ArrayList();
        arrList1.add("one");
        arrList1.add("Two");
        arrList1.add("Three");

        arrList2.addAll(arrList1);
        arrList1.remove(1);
        System.out.println(arrList2.size());
        System.out.println(arrList1.size());
        Iterator it1=arrList1.iterator();
          while(it1.hasNext()){
            System.out.println(it1.next());
        }
    }
}

List集合

List是一个有序,可重复的集合。List有两个实现类ArrayList和LinkedList类。

ArrayList

ArrayList实现了可变数组的大小,提供了基于索引访问元素,对后进先出的支持较好。

 ArrayList的方法
  
   get 获取指定下标的元素
   index 获取指定元素的下标(有多个则返回第一个)
   lastIndexOf 返回最后一次出现指定元素的下标
   set 修改执行下标的元素
   subList(start,end) 返回一个新的集合,集合中包含从startend下标的所有元素
import java.util.ArrayList;
import java.util.Iterator;

public class SetDemo {
    public static void  main(String [] args){
        ArrayList arrList1=new ArrayList();
        Product pd1=new Product("手机",0, 12.5);
        Product pd2=new Product("电脑",1,13.6);
        Product pd3=new Product("平板",2,66.6);
        arrList1.add(pd1);
        arrList1.add(pd2);
        arrList1.add(pd3);
        arrList1.add(pd1);
        System.out.println("对象第一次出现的位置"+arrList1.indexOf(pd1));
        System.out.println("对象第二次出现的位置"+arrList1.lastIndexOf(pd1));
        System.out.println("商品信息");
        for (int i=0;i<arrList1.size();i++){
            Product product=(Product) arrList1.get(i);
            //因为从集合里获取到的是Object类型,所以需要向下转型才能调用到Product里的方法
            System.out.println(product.getInfo());
        }
    }
}

class Product{
    private String name;
    private int id;
    private double price;

    public Product(String name,int id ,double price){
         this.name=name;
         this.id=id;
         this.price=price;
    }

    public String getInfo(){
        return  "商品名称:"+this.name+"商品编号:"+this.id+"商品价格:"+this.price;
    }
}

LinkedList类

LinkedList采用链表结构保存对象

 常用方法
  
    
     addFirst 将指定元素添加到集合开头
     addLast 将指定元素添加到集合末尾
     getFirst 返回集合的第一个元素
     getLast 返回集合的最后一个元素
     removerFirst 删除集合的第一个元素
     removeLast 删除集合的最后一个元素

public class SetDemo {
    public static void  main(String [] args){
        LinkedList<String> linkList=new LinkedList<String>();
        linkList.add("螺丝");
        linkList.add("螺母");
        linkList.add("扳手");
        linkList.add("铁锹");
        linkList.add("砍刀");
        //向开头添加
        linkList.addFirst("文件夹");
        //向末尾添加
        linkList.addLast("工具书");
        System.out.println("目前所有的商品有");
        for(int i=0;i<linkList.size();i++){
            System.out.println(linkList.get(i));
        }
        //删除最后一个元素
        linkList.removeLast();
        System.out.println("删除最后一个元素还有");
        for (int j=0;j<linkList.size();j++){
            System.out.println(linkList.get(j));
        }
    }
}

ArrayList和LinkedList的区别

ArrayList是基于数组的数据结构实现的,访问速度要有优于LinkedList 。 LinkedList是基于链表的数据结构实现的,占用的内存比较大,但是在于批量添加和删除要优于ArrayList

Set

Set类似于Js的Set,Set是无序的,但是Set里不能包含重复的元素。java里的Set有HashSet和TreeSet两个实现类

HashSet

HashSet是最常用的Set集合,HashSet是在按照Hash算法来存储集合中的元素,具有很好的存取和查找性能。

HashSet里存储的元素是无序的,而且HashSet不是同步的,如果多个线程同时访问或者修改同一个

HashSet,则必须通过代码来保证同步,元素值可以是null。

当向HashSet存入一个元素时,HashSet会调用hashCode方法得到hashcode值,hahscode值决定元素存储的位置。

如果两个元素的值相等,但是hashCode值不相等,那么HashSet就认为这两个元素是不相等的。
public class SetDemo {
    public static void  main(String [] args){
        HashSet <String> hashset=new HashSet<String>();
        hashset.add("语文");
        hashset.add("数学");
        hashset.add("英语");
        hashset.add("语文");
        //如果添加两个相同的元素,那么最后一个会覆盖掉前一个元素
        System.out.println("课程表里有");
        Iterator hashIter=hashset.iterator();
        while(hashIter.hasNext()){
            System.out.println(hashIter.next());
        }
        System.out.println("共"+hashset.size()+"门课");
    }
}

TreeSet

TreeSet同时实现了Set接口和SortedSet,SortedSet接口是Set接口的子接口,可以实现对集合进行自然排序,TreeSet只能对实现了Comparable接口的类对象进行排序。

  常用的方法
    
    first
    last
    poolFirst 获取并移除集合中的第一个元素
    poolLast 获取并移除集合中的最后一个元素
    subSet(start,end) 返回一个新集合,集合中包含从startend的所有元素
    headSet 返回一个新的集合,集合中包含指定元素之前的所有元素,不包含指定元素。
    tailSet 返回一个新的集合,集合中包含指定元素之后的所有元素,包含指定元素。
    
    在使用自然排序时只能向集合中添加相同数据类型的对象,否则会报错
public class SetDemo {
    public static void  main(String [] args){
        TreeSet <Double> treeSet=new TreeSet<Double>();
        System.out.println("学生成绩查询系统");
        Scanner input=new Scanner(System.in);
        for (int i=0;i<5;i++){
            System.out.print("请输入第"+(i+1)+"个学生的成绩");
            double student=input.nextDouble();
            treeSet.add(student);
        }
        System.out.println("所有学生的成绩为");
        Iterator it=treeSet.iterator();
        while(it.hasNext()){
            System.out.print(it.next()+"\t");
        }
        System.out.println("请输入要查询的成绩");
        double cj=input.nextDouble();
        if(treeSet.contains(cj)){
            System.out.println("成绩为"+cj+"的学生存在");
        }else{
            System.out.println("成绩为"+cj+"的学生不存在");
        }
        SortedSet<Double> newTreeSet=treeSet.headSet(60.0);
        System.out.println("不及格的学生有");
        Iterator newIt=newTreeSet.iterator();
        while(newIt.hasNext()){
            System.out.println(newIt.next()+"\t");
        }
        SortedSet<Double> newTwoSet=treeSet.tailSet(90.0);
        System.out.print("成绩大于90的学生有");
        Iterator newTwoIt=newTwoSet.iterator();
        while(newTwoIt.hasNext()){
            System.out.println(newTwoIt.next()+"\t");
        }
    }
}

Map

Map是一个键值对的集合,用于保存具有映射关系的数据。 Map主要实现两个接口,HashMap类和TreeMap,HashMap类按照Hash算法来存取键值对,TreeMap可以对键值对进行排序。

常用方法

clear 删除该Map对象中所有的键值对
containsKey 查询Map中是否包含指定的Key
containsValue 查询Map中是否包含一个或者多个value
get 返回Map集合中指定键值对的值
put 向Map集合中添加键值对,如果有相同的key则会覆盖掉之前的键值对
putAll  将指定Map中的中的键值对赋值到本Map中
remove 从Map集合中删除指定key对应的键值对,
entrySet 返回Map中所有的键值对的Set集合
KeySet 返回集合中所有键对象的Set集合
isEmpty 判断Map是否为空
size 返回键值对的个数
values 返回value组成的Collection
public class SetDemo {
    public static void  main(String [] args){
        HashMap hashMap=new HashMap();
        hashMap.put("11","刘能");
        hashMap.put("22","谢广坤");
        hashMap.put("33","苏大强");
        hashMap.put("66","范德彪");
        System.out.println("**************学生列表***********");
        Iterator it1=hashMap.keySet().iterator();
        while(it1.hasNext()){
            Object key=it1.next();
            Object value=hashMap.get(key);
            System.out.println("学号:"+key + "姓名:"+value);
        }
        System.out.println("请输入要删除的学号");
        Scanner input=new Scanner(System.in);
        String xh=input.next();
        if(hashMap.containsKey(xh)){
            hashMap.remove(xh);
        }else{
            System.out.println("该学生不存在");
        }
        System.out.println("删除后的学生列表");
        Iterator it2=hashMap.keySet().iterator();
        while(it2.hasNext()){
            Object h=it2.next();
            Object name=hashMap.get(h);
            System.out.println("学号:"+h + "姓名:"+name);
        }
    }
}

新增的Map方法

getOrDefault(key,"d");

如果指定的key存在则返回value,不存在则返回指定的值

System.out.println(hashMap.getOrDefault("77","不存在"));

forEach

遍历集合的方法,参数是一个lemada表达式

   hashMap.forEach((key,value)->{
            System.out.println(key+value);
        });

replaceAll

替换集合中的所有value值

  hashMap.replaceAll((key,value)->"哈哈");

putlfAbsent

如果key关联的value不存在,则关联新的value

  hashMap.put("11",null);
        hashMap.put("22","谢广坤");
        hashMap.put("33","苏大强");
        hashMap.put("66","范德彪");
        hashMap.putIfAbsent("11","哈哈");
        hashMap.forEach((key,value)->{
            System.out.println(key+value);
        });

replace

 replace(key,value); //将key值对应的value替换为新的value
 replace(key,oldvalue,newvalue);// 如果key值对应的value与oldvalue相等则替换成newvalue

遍历Map

遍历Map集合除了使用Iterator遍历还有使用entyr遍历和forEach遍历

使用entry遍历

Map<String,String> hashMap=new HashMap<String,String>();
        hashMap.put("11","刘能");
        hashMap.put("22","谢广坤");
        hashMap.put("33","苏大强");
        hashMap.put("66","范德彪");
        for(Map.Entry<String,String> entry : hashMap.entrySet()){
           String key=entry.getKey();
           String value=entry.getValue();
           System.out.println("学号:"+key+"姓名 : " + value);
        }

forEach遍历

Map<String,String> hashMap=new HashMap<String,String>();
        hashMap.put("11","刘能");
        hashMap.put("22","谢广坤");
        hashMap.put("33","苏大强");
        hashMap.put("66","范德彪");
        for(String key : hashMap.keySet()){
            System.out.println(key);
        }
        for(String value : hashMap.values()){
            System.out.println(value);
        }Map<String,String> hashMap=new HashMap<String,String>();
        hashMap.put("11","刘能");
        hashMap.put("22","谢广坤");
        hashMap.put("33","苏大强");
        hashMap.put("66","范德彪");
         hashMap.forEach((key,value)->{
            System.out.println(key+value);
        });

Collections

Collections类是java提供的一个操作Set,List和Map等集合的工具类

排序的方法

reverse 对指定List集合元素进行逆向排序
shuffe 对List集合元素进行随机排序
sort 根据元素的自然顺序对指定List集合进行升序排序
sort(list,Comparator c) 根据Comparator产生的顺序对List集合元素进行排序
swap(list ,i ,j) 将指定List集合的下标i的元素和下表j的元素换位置
rotate (list , s) 当s为正数时,将list集合的后s各元素移动到前面,为负数时将前s个元素整体移到后边
public class SetDemo {
    public static void  main(String [] args){
     List prices=new ArrayList();
     Scanner input=new Scanner(System.in);
     for (int i=0;i<5;i++){
         System.out.print("请输入第"+(i+1)+"个商品的价格");
         prices.add(input.nextInt());
     }
     Collections.sort(prices);
     System.out.println("从低到高的排序是");
     Iterator it1=prices.iterator();
     while(it1.hasNext()){
         System.out.print(it1.next()+"\t");
     }
     System.out.print("翻转操作");
     Collections.reverse(prices);
        Iterator it2=prices.iterator();
        while(it2.hasNext()){
            System.out.print(it2.next()+"\t");
        }
    }
}

查找和替换的方法

binarySearch 使用二分搜索指定的集合,获取指定对象在 List中的下标,使用该方法List必须是有序的

max 根据元素的自然顺序,返回集合中的最大元素

max(Collection coll, Comparator comp) 根据指定的comp指定的顺序,返回集合中的最大元素

min

min(Collection coll,Comparator comp)

fill(list ,obj) 使用指定元素obj替换list中的所有元素

frequency(list,obj) 返回list集合中指定元素obj的出现次数

indexOfSubList(father,child) 返回子集合child在父集合father中第一次出现的下标

indexOfSubList(father,child) 最后一次出现的下标

replaceAll(list,oldval,newVal) 使用newVal替换list中所有的oldVal

//fill方法
public class SetDemo {
    public static void  main(String [] args){
     List goods=new ArrayList();
     Scanner input=new Scanner(System.in);
     for (int i=0;i<5;i++){
         System.out.print("请输入第"+(i+1)+"个商品名称");
         goods.add(input.next());
     }
     Collections.fill(goods,"未填写");
     System.out.print("替换后的商品信息");
     Iterator it1= goods.iterator();
     while(it1.hasNext()){
      System.out.print(it1.next()+"\t");
     }
    }

}

//max,min,replaceAll,binarySearch 方法
 List goods = new ArrayList();
        goods.add(3);
        goods.add(1);
        goods.add(2);
        goods.add(3);
        goods.add(6);
        System.out.println(Collections.max(goods)); //输出最大元素
        System.out.println(Collections.min(goods)); //输出最小元素
        System.out.println(Collections.frequency(goods,3)); //输出元素出现的次数
        Collections.replaceAll(goods,3,8);
        Collections.sort(goods);//先排序
        System.out.println(goods);

        //再用二分搜索查找
        System.out.println(Collections.binarySearch(goods,6));

copy

copy方法,用于将指定集合,复制到另一个集合中,copy方法中已经复制的元素的下标,向党羽源集合中的下标,如果源集合的下标有元素将会被替换

Iterator

一直在使用Iterator迭代器进行遍历集合元素,Iterator是一个接口有四个方法

hasNext 如果元素没有被遍历完则返回true

next 返回集合里的下一个元素

remove 删除集合里的上一次next方法返回的元素

forEachRemaining 使用lambad表达式遍历集合元素

如果正在使用迭代器遍历集合则不能改变集合只能用迭代器提供的remove方法,否则会报错

forEachRemaining

forEachRemaining是使用Lambda表达式来遍历集合元素

public class SetDemo {
    public static void  main(String [] args) {
        List goods = new ArrayList();
        goods.add(3);
        goods.add(1);
        goods.add(2);
        goods.add(3);
        goods.add(6);
       Iterator it= goods.iterator();
       it.forEachRemaining(obj->{
           System.out.println(obj);
       });
    }
}

forEach遍历Collection集合元素

 Collection goods = new HashSet<>();
        goods.add("1");
        goods.add("2");
        goods.add("3");
        goods.add("4");
        goods.add("5");
       for(Object obj:goods){
           String obj1=(String) obj;
           System.out.println(obj1);
       }

Predicate

Predicate是用来操作Collection集合的一个接口,Predicate方法Lambda表达式作为参数。主要是用于判断一个参数是否符合要求。

import java.util.*;
import java.util.function.Predicate;

public class SetDemo {
    public static void  main(String [] args) {
        Collection objs = new HashSet();
        objs.add(new String("乡村爱情刘能"));
        objs.add(new String("乡村爱情赵四"));
        objs.add(new String("乡村爱情谢广坤"));
        objs.add(new String("乡村爱情王老七"));
        objs.add(new String("乡村爱情王大拿"));

        System.out.println(calAll(objs,ele->((String) ele).length() >6));
        System.out.println(calAll(objs,ele->((String) ele).contains("王大拿")));
        System.out.println(calAll(objs,ele->((String) ele).contains("赵四")));


    }
    public static int calAll(Collection objs, java.util.function.Predicate p) {
        int total = 0;
        for (Object obj : objs) {
            // 使用Predicate的test()方法判断该对象是否满足Predicate指定的条件
            if (p.test(obj)) {
                total++;
            }
        }
        return total;
    }
}

Stream操作Collection集合

java里提供了Stream,IntStream,LongStream,DoubleStream等流式API,这些Api代表多个支持串行和并行的操作的元素,Stream是一个通用的流接口。 流式API还创建的对应的Builder可以通过Builder创建对应的流

 使用流的步骤

  1. 使用Stream或者xxxStream的builder方法创建该流对应的Builder
  2. 重复调用Builder方法的add方法添加元素
  3. 调用Builder的build方法,获取对应的Stream
  4. 调用Steram的方法来写业务逻辑
//聚集方法一次只能执行一行,否则会报错
     IntStream is=IntStream.builder().add(1).add(20).add(6).build();
        System.out.println(is.max().getAsInt());
//        System.out.println(is.min().getAsInt());
//        System.out.println(is.sum());
//        System.out.println(is.count());
//        IntStream newIs=is.map(ele->{
//            return ele*2;
//        });

常用的中间方法

filter(Predicate p) 过滤不符合predicate的元素

mapToXxx(ToXxxFunction mapper) 使用ToXxxFunction对流中的元素执行一对一的转换,该方法返回的新流中包含可ToXxxxFunctiion转换生成的所有元素

peek(Consumer action) 一次对每个元素执行一些操作

distinct 排序流中所有重复的元素

sorted 用于保证流中的元素在后序的访问中处于有序状态

limit 用于保证对该流的后序访问中最大允许访问的元素个数

常见的末端方法

forEach 遍历流中所有元素

toArray 将流中所有元素转换为一个数组

reduce 通过某种操作合并流中的元素

min 返回流中最小的元素

max 返回流中最大的元素

count 返回流中所有元素的数量

anyMatch(predicate) 判断流中是否至少包含一个元素符合Predicate条件

allMatch(Predicate) 判断流中是否每个元素都符合Predicate条件

noneMatch(Predicate) 判断流中是否所有元素都不符合Predicate条件

findFirst 返回流中的第一个元素

findAny 返回流中的任意一个元素

   Collection objs = new HashSet();
        objs.add(new String("乡村爱情刘能"));
        objs.add(new String("乡村爱情赵四"));
        objs.add(new String("乡村爱情谢广坤"));
        objs.add(new String("乡村爱情王老七"));
        objs.add(new String("乡村爱情王大拿"));

        System.out.println(objs.stream().filter(ele->((String) ele).contains("乡村爱情")).count());
        System.out.println(objs.stream().filter(ele->((String) ele).contains("王大拿")).count());
        System.out.println(objs.stream().filter(ele->((String) ele).length()>6).count());
        objs.stream().mapToInt(ele->(((String) ele).length())).forEach(item->{
            System.out.println(item);
        });

创建不可变集合

可以通过集合的of方法直接创建不可变集合,不可变也就意味着不能向集合中添加元素,也不能删除元素

    Set set=Set.of(1,2,3);
       List list=List.of(4,5,6);
       System.out.println(set);
       System.out.println(list);
       Map map1=Map.of("哈哈",1,"哈哈2",2);
       System.out.println(map1);
       Map map2=Map.ofEntries(Map.entry("滴滴",1),Map.entry("滴滴2",2));
       System.out.println(map2);
       //如果向不可变集合里添加元素,或者删除元素,则会报错

泛型

java的集合有个缺点,就是把一个对象丢就集合里,再取出来时,对象就变成了Object类型,所以集合里没有类型限制,这就有了泛型

泛型集合

泛型本质上是提供类型的类型参数,也就是参数化类型

public class SetDemo {
    public static void  main(String [] args) {
        Product p1=new Product("手机",1,12.0);
        Product p2=new Product("电脑",2,22.0);
        Product p3=new Product("ipad",1,32.0);
        Map<Integer,Product> products=new HashMap<Integer, Product>();
        /*
        在声明集合时,定义集合的泛型,
        指定该Map的key 是Integer类型,value是Product类型。在put时如果不是这俩类型则会报错
        */
        products.put(1,p1);
        products.put(2,p2);
        products.put(3,p3);
        Iterator it1=products.keySet().iterator();
        while(it1.hasNext()){
            Object key=it1.next();
            System.out.println("key值: "+key+"Values : "+products.get(key).getInfo());
        }
    }

}

//定义了一个product类,包含product信息
class Product{
    private String name;
    private int id;
    private double price;

    public Product(String name,int id ,double price){
         this.name=name;
         this.id=id;
         this.price=price;
    }

    public String getInfo(){
        return  "产品名称:"+this.name+"产品编号:"+this.id+"产品价格:"+this.price;
    }
}

泛型类

泛型类一般用于,类中的属性不确定的情况下。

public class SetDemo {
    public static void  main(String [] args) {
        Product<String,Integer,Double> p1= new Product<String,Integer,Double>("手机", 1, 12.0);
        System.out.println(p1.getInfo());
    }

}


class Product<A,B,C>{
    private A name;
    private B id;
    private C price;

    public Product(A name,B id ,C price){
         this.name=name;
         this.id=id;
         this.price=price;
    }

    public String getInfo(){
        return  "产品名称:"+this.name+"产品编号:"+this.id+"产品价格:"+this.price;
    }
}

泛型方法

public class SetDemo {
    public static void  main(String [] args) {
        Product p1= new Product("手机", 1, 12.0);
       list(p1);
    }
    public static <T> void list(T product){
         System.out.println(product);
    }
}


class Product{
    private String name;
    private int id;
    private double price;

    public Product(String name,int id ,double price){
         this.name=name;
         this.id=id;
         this.price=price;
    }
    public String toString(){
        return  "产品名称:"+this.name+"产品编号:"+this.id+"产品价格:"+this.price;
    }
}

限制泛型可用类型

public class SetDemo<T extends List> {
    public static void  main(String [] args) {
       SetDemo<ArrayList> st1=new SetDemo<ArrayList>();
       SetDemo<LinkedList> st2=new SetDemo<LinkedList>();
       // 定义了SetDemo类,并对该类的限制是必须是实现了List接口的类
        // 因此在实例化时,泛型必须是实现了Lisy接口
    }
}

枚举

枚举是一个被命名的整型常数的集合,用于声明一组带标识符的常数。

声明枚举

声明枚举必须使用enum关键字

public class enumDemo {
    public static void main(String [] args){
        System.out.println(enumName.Re);
    }
    public enum enumName{
         Re
    }
}

枚举类

java中的每一个枚举都继承自java.lang.Enum类,当定义一个枚举类型时,每一个枚举成员都可以看作是Enum类的实例,当使用枚举类型成员时,直接使用枚举名调用成员。

  枚举类的常用方法
    
    values 以数组形式返回枚举类型的所有成员
    valueOF 将普通字符串转换为枚举实例
    compareTo 比较两个枚举成员在定义时的顺序
    ordinal 获取枚举成员的下标
public class enumDemo {
    public static void main(String [] args){
      
       for(int i=0;i<enumName.values().length;i++){
           System.out.println(enumName.values()[i].ordinal());
           System.out.println(enumName.values()[i]);
       }
    }
    public enum enumName{
         Re,Ea,Qw
    }
}

为枚举添加方法

java为枚举类型添加了一些方法,同样,枚举常量也可以有自己的方法。添加枚举方法必须要先定义枚举实例,而且要在最后一个成员后添加分号

import java.security.PublicKey;

public class enumDemo {
    public static void main(String [] args){

        for(enumName day : enumName.values()) {
            System.out.println(day+"====>" + day.getDay());
        }
        enumName.printDay(5);
    }
    public enum enumName{
        One("周一"),Two("周二"),Three("周三"),Four("周四"),Five("中午"),Sex("周六"),Sunday("周日");
       private final String day;
        enumName(String day) {
            this.day=day;
        }
        public static void printDay(int i){
          switch (i){
              case 1 :
                  System.out.println(enumName.One);
                  break;
              case 2 :
                  System.out.println(enumName.Two);
                  break;
              case 3 :
                  System.out.println(enumName.Three);
                  break;
              case 4 :
                  System.out.println(enumName.Four);
                  break;
              case 5 :
                  System.out.println(enumName.Five);
                  break;
              case 6 :
                  System.out.println(enumName.Sex);
                  break;
              case 7 :
                  System.out.println(enumName.Sunday);
                  break;
              default:
                  System.out.println("没有这个日期");

          }
        }
        public String getDay(){
            return day;
        }
    }
}

EnumMap与EnumSet

为了更好的支持枚举,java提供了EnumMap 和EnumSet HashMap只能接收统一枚举类型的实例作为键值

EnumMap

// HashMap例子
import java.security.PublicKey;
import java.util.EnumMap;

public class enumDemo {
   public static void main(String [] args){
    enumDemo test=new enumDemo();
    test.setMaps();
    System.out.println(test.maps.get(enumName.Four));
   }
   public void setMaps(){

        maps.put(enumName.Two,"2");
       maps.put(enumName.Three,"3");
       maps.put(enumName.Sunday,"4");
       maps.put(enumName.Five,"5");
       maps.put(enumName.Four,"6");
       maps.put(enumName.Sex,"7");
    }
   private EnumMap<enumName,String> maps = new EnumMap<enumName,String>(enumName.class);
   public enum enumName{
       One("周一"),Two("周二"),Three("周三"),Four("周四"),Five("中午"),Sex("周六"),Sunday("周日");
      private final String day;
       enumName(String day) {
           this.day=day;
       }
       public static void printDay(int i){
         switch (i){
             case 1 :
                 System.out.println(enumName.One);
                 break;
             case 2 :
                 System.out.println(enumName.Two);
                 break;
             case 3 :
                 System.out.println(enumName.Three);
                 break;
             case 4 :
                 System.out.println(enumName.Four);
                 break;
             case 5 :
                 System.out.println(enumName.Five);
                 break;
             case 6 :
                 System.out.println(enumName.Sex);
                 break;
             case 7 :
                 System.out.println(enumName.Sunday);
                 break;
             default:
                 System.out.println("没有这个日期");

         }
       }
       public String getDay(){
           return day;
       }
   }
}

EnumSet

EnumSet是枚举类型的高性能Set实现,它要求放入它的枚举常量必须属于同一枚举类型

 常用方法

   allOf() 创建一个包含指定枚举类型中所有枚举成员的EnumSet对象

   complementOf(EnumSet<E> s) 创建一个与指定EnumSet对象s相同的枚举类型EnumSet对象,并包含s中未包含的枚举成员

   copeOf  创建一个与指定EnumSet对象相同的EnumSet包含指定EnumSet对象的所有成员

   noneOf 创建指定枚举类型的空EnumSet对象

   of(a,b) 创建包含指定枚举成员ab的EnumSet对象

   range(start,end) 创建一个EnumSet对象,该对象包含了从start到end的多有枚举成员

一对多的关系

现实中,一对多的关系有很多例子,比如:一个学校有多个学生,一个学生属于一个学校这就是一对多。可以通过集合进行关系的表示。

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class StudentDemp {
 public static void main(String [] args){
     //创建学校
     School sch=new School("家里蹲大学");
    //创建学生
     Student s1=new Student("张三",19);
     Student s2=new Student("里斯",21);
     Student s3=new Student("王五",22);
     //学校里添加学生
     sch.studentListAdd(s1);
     sch.studentListAdd(s2);
     sch.studentListAdd(s3);
     //设置学生的学校
     s1.setSchool(sch);
     s2.setSchool(sch);
     s3.setSchool(sch);
     //学校信息
     System.out.println(sch);
     List list=sch.getStudentList();
     Iterator it1= list.iterator();
     while(it1.hasNext()){
         System.out.println(it1.next());
     }

 }
}
/*学生类*/
class Student{
   private String name; //学生姓名
   private int age;//学生年龄
   private  School school;//所属学校
   public Student(String name,int age){
       this.setName(name);
       this.setAge(age);
   }

   @Override
   public String toString() {
       return "学生姓名:\t"+this.getName()+"\t年龄"+this.getAge();
   }
   public String getName() {
       return this.name;
   }
   public int getAge(){
       return this.age;
   }
   public void setName(String name){
       this.name=name;
   }
   public void setSchool(School school){
       this.school=school;
   }
   public void setAge(int age){
       this.age=age;
   }
}
/*学校类*/
class School{
private String name; //学校名称
private List<Student> studentList; //学生列表
   public School(String name){
         this.name=name;
       this.studentList = new ArrayList<Student>();
   }
  public List<Student> getStudentList(){
       return this.studentList;
  }
  public void studentListAdd(Student s){
       this.studentList.add(s);
  }
   @Override
   public String toString() {
       return "学校名称\t"+this.name;
   }
}


多对多的关系

业务中多对多的关系也不少,比如、:一个学生可以参加多个课程,一个课程也可以有多个学生

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class StudentDemp {
  public static void main(String [] args){
      StudentDemp n=new StudentDemp();
      //创建课程
 Course c1=new Course("数学",3);
 Course c2=new Course("英语",6);
     //创建学生
 Student s1=new Student("刘能",20);
 Student s2=new Student("赵四",22);
 Student s3=new Student("王大拿",36);
 Student s4=new Student("王老七",32);
 Student s5=new Student("宋晓锋",26);
 Student s6=new Student("谢永强",20);
 //数学课程,添加五个学生
      c1.getAllStudent().add(s1);c1.getAllStudent().add(s3);
      c1.getAllStudent().add(s5);c1.getAllStudent().add(s4);
      c1.getAllStudent().add(s6);
 //英语课程添加三个学生
      c2.getAllStudent().add(s1);c2.getAllStudent().add(s2);c2.getAllStudent().add(s3);
      //学生添加课程
      s1.getAllCourse().add(c1);s1.getAllCourse().add(c2);
      s4.getAllCourse().add(c1);
      s3.getAllCourse().add(c1);s3.getAllCourse().add(c2);
      s5.getAllCourse().add(c1);
      s6.getAllCourse().add(c1);
      s2.getAllCourse().add(c2);
      // 输出课程下的所有学生
      System.out.println("*********************所有课程***********");
      Iterator<Student> it1=c1.getAllStudent().iterator();
      System.out.println(c1);
      n.prints(it1);
      System.out.println(c2);
      Iterator<Student> it2=c2.getAllStudent().iterator();
      n.prints(it2);
      //输出一个学生的课程信息
      System.out.println("**********刘能的课程信息*******");
      Iterator<Course> it3=s1.getAllCourse().iterator();
      System.out.println(s1);
      n.prints(it3);

  }
  public void prints(Iterator s){
          while(s.hasNext()){
              System.out.println(s.next());
          }
  }
}
/*学生类*/
class Student{
 private String name; //学生名称
 private int age; //学生年龄
 private List<Course> allCourse; //学生的课程集合
 public Student(){
     this.allCourse=new ArrayList<Course>();
 }
 public Student(String name,int age){
     this();
     this.setName(name);
     this.setAge(age);
 }
 public String getName(){return this.name;}
 public int getAge(){return this.age;}
 public void setName(String name){this.name=name;}
 public void setAge(int age){this.age=age;}
 public List<Course> getAllCourse(){return this.allCourse;}
 public void setAllCourse(List<Course> list){this.allCourse=list;}
 public String toString(){return "学生姓名\t\t"+this.name+"\t\t学生年龄\t\t"+this.age;}
}
class Course{
 private String name;
 private int credit;
 private List<Student> allStudent;
 public Course(){
     this.allStudent=new ArrayList<Student>();
 }
 public Course(String name,int credit){
     this();
     this.setCredit(credit);
     this.setName(name);
 }
 public String getName(){return this.name;}
 public int getCredit(){return this.credit;}
 public List<Student> getAllStudent(){return this.allStudent;}
 public void setName(String name){this.name=name;}
 public void setCredit(int credit){this.credit=credit;}
 public void setAllStudent(List<Student> list){this.allStudent=list;}

    @Override
    public String toString() {
        return "课程名称:\t\t"+this.name+"\t\t学分:\t\t"+this.credit;
    }
}