• Java 基础知识总结 3


    13.java类集

        类集实际上是一个动态的对象数组,与一般的对象数组不同,类集中的对象内容可以任意扩充.

    • 类集的特征:
      • 1)这种框架是高性能的
      • 2)框架必须允许不同类型的类集以相同的方式和高度互操作方式工作.
      • 3)类集必须是容易扩展和修改的
    • 类集框架的主要接口:
      • 1)Collection 是存放一组单值的最大接口,所谓的单值是指集合中的每个元素都是一个对象,一般很少会置接使用此接口直接操作.
      • 2)List 是Collection接口的子类,没有对Collection接口进行扩充,里面允许存放重复的内容.
      • 3)Set 是Collection接口的子类,没有对Collection接口进行扩充,里面不允许存放重复内容.
      • 4)Map 是存放一对值的最大接口,即接口中的每个元素都是一对,以Key -> value的形式保存.
      • 5)Iterator 集合的输出接口,用于输出集合中的内容,只能进行从前到后的单向输出.
      • 6)ListIterator 是Iterator的子接口,可以进行双向输出.
      • 7)Enumeration 是最早的输出接口,用于输出指定集合中的内容.
      • 8)SortedSet 单值的排序接口,实现此接口的集合类,里面的内容是可以排序的,使用比较器排序.
      • 9)Queue 队列接口,此接口的子类可以实现队列操作.
      • 10)Map.Entry 的内部接口,每个Map.Entry对象都保存着一对Key -> value的内容,每个Map接口中都保存多个Map.Entry接口实例.
    1. Collection类
        • Collection是保存单值集合的最大父类接口
        • 定义:public interface Collection<E> extends Iterable<E>
        • 方法:
      1)public boolean add(E o) //向集合中插入对象.
      2)public boolean addAll(Collection<? extends E> c)// 将一个集合的内容插入进来
      3)public void clear() //清除次集合中的所有元素.
      4)public boolean contains(Object 0) //判断某一个对象是否在集合中存在
      5)public boolean containsAll(Collection<?> c) //判断一组对象是否在集合中存在.
      6)public boolean equals(Object o)// 对象比较
      7)public int hashCode() //哈希码
      8)public boolean isEmpty() //集合是否为空
      9)public Iterator<E> iterator() //为Iterator接口实例化
      10)public boolean remove(Object o) //删除指定对象
      11)public boolean removeAll(Collection<?> c)// 删除一组对象
      12)public boolean retainAll(collection<?> c) //保存指定内容
      13)public int size() //求出集合的大小
      14)public Object[] toArray() //将一个集合变成对象数组
      15)public <T> T[] toArray(T[] a) //指定好返回的对象数组类型
          在开发中很少使用Collection接口进行开发.一般都使用其子类:
      1)List
        • 可以放任意数据,在List接口中内容是允许重复的.
        • List接口的扩展方法
        • public void add(int index, E element) //在指定位置增加元素
          public boolean addAll(int index,Collection<? extends E > c) //在指定位置增加一组元素
          E get(int index) //返回指定位置的元素
          public int indexOf(Object o) //查找指定元素的位置.
          public intlastIndexOf(Object o) //从后向前查找指定元素的位置.
          public ListIterator<E> listIterator()// 为ListIterator接口实例化
          public E remove(int index) //按指定的位置删除元素
          public List<E> subList(int fromIndex,int toIndex) //取出集合中的子集合
          public E set(int index,E element)//替换指定位置的元素
        • ArrayList子类
          • 通过对象的多态性,为List接口实例化
          • 定义:public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess,Cloneable,Serializable
          • 示例1:
          • public static void main(String args[]){
                List<String> allList = null ;
                Collection<String> allCollection = null ;
                allList = new ArrayList<String>() ;    // 指定操作的泛型为String
                allCollection = new ArrayList<String>() ;    // 指定一个集合
                allList.add("Hello") ;    // 此方法由Collection接口而来
                allList.add(0,"World") ;    // 在第一个位置上添加新的内容
                System.out.println(allList) ;
                allCollection.add("LXH") ;    // 向Collection中加入内容
                allCollection.add("www.mldn.cn") ;
                allList.remove(0) ; // 删除第一个元素,指定删除的位置
                allList.remove("Hello") ;    // 此方法由Collection接口继承而来
                allList.addAll(allCollection) ;
                allList.addAll(0,allCollection) ;
                System.out.println(allList) ;
                for(int i=0;i<allList.size();i++){
                    System.out.print(allList.get(i) + "、") ;
                }
            }
          • 示例2:
          • public static void main(String args[]){
                List<String> allList = null ;
                allList = new ArrayList<String>() ;    // 指定操作的泛型为String
                System.out.println("集合操作前是否为空?" + allList.isEmpty()) ;
                allList.add("Hello") ;    // 此方法由Collection接口而来
                allList.add(0,"World") ;    // 在第一个位置上添加新的内容
                allList.add("MLDN") ;    // 向Collection中加入内容
                allList.add("www.mldn.cn") ;
                System.out.println(allList.contains("Hello")?""Hello"字符串存在!" : ""Hello"字符串不存在!") ;
                List<String> allSub = allList.subList(2,3) ;    // 字符串截取
                System.out.println("集合截取:") ;
                for(int i=0;i<allSub.size();i++){
                    System.out.print(allSub.get(i) + "、") ;
                }
                System.out.println("MLDN字符串的位置:" + allList.indexOf("MLDN")) ;
                System.out.println("集合操作后是否为空?" + allList.isEmpty()) ;
            }
      • 2)Set
        • 定义:public interface Set<E> extends Collection<E>
        • 子类:
          • HashSet 散列存放
          • TreeSet 有序存放
          • TreeSet要想实现排序的操作,则要对象所在的类也必须实现Comparable接口.
          • String 类实现了Comparable接口.
          • hashCode() 表示一个唯一的编码,一般通过计算表示
          • equals() 进行对象的比较操作
          • 示例:
          • import java.util.Set ;
            import java.util.TreeSet ;
            class Person implements Comparable<Person>{
                private String name ;
                private int age ;
                public Person(String name,int age){
                    this.name = name ;
                    this.age = age ;
                }
                public String toString(){
                    return "姓名:" + this.name + ";年龄:" + this.age ;
                }
                public int compareTo(Person per){
                    if(this.age>per.age){
                        return 1 ;
                    }else if(this.age<per.age){
                        return -1 ;
                    }else{
                        return this.name.compareTo(per.name) ;    // 调用String中的    compareTo()方法
                    }
                }
            };
            public class TreeSetDemo04{
                public static void main(String args[]){
                    Set<Person> allSet = new TreeSet<Person>() ;
                    allSet.add(new Person("张三",30)) ;
                    allSet.add(new Person("李四",31)) ;
                    allSet.add(new Person("王五",32)) ;
                    allSet.add(new Person("王五",32)) ;
                    allSet.add(new Person("王五",32)) ;
                    allSet.add(new Person("赵六",33)) ;
                    allSet.add(new Person("孙七",33)) ;
                    System.out.println(allSet) ;
                }
            };
      • 3)Queue
        • LinkedList表示的是一个链表的操作类,定义如下:
        • public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>,Queue<E>,Cloneable,Serializable
        • 1)public void addFirst(E o) //在链表开头增加元素
          2)public void addLast(E o) //在链表结尾增加元素
          3)public boolean offer(E o) //将指定元素增加到链表的结尾
          4)public E removerFirst() //删除链表的第一个元素
          5)public E removeLast() //删除链表的最后一个元素
        • Queue接口是Collection的子接口,此接口定义如下:
        • public interface Queue<E> extends Collection<E>
        • 1)public E element() //找到链表的表头
          2)public boolean offer(E o) //将指定元素增加到链表的结尾
          3)public E peek() //找到但并不删除链表的头
          4)public E poll() //找到并删除此链表的头
          5)public E remove() //检索并移除表头
      • 4)SortedSet
        • 一、方法:
        • public Comparator<? super E> comparator() //返回与排序有关联的比较器
          public E first()// 返回集合中的第一个元素
          public SortedSet<E> headset(E toElement) //返回从开始到指定元素的集合
          public E last() //返回最后一个元素
          public SortedSet<E> subSet(E fromElement,E toElement) //返回指定对象间的元素
          public SortedSet<E> tailSet(E fromElement) //从指定元素到最后
        • 二、只要看见了以Sorted开头的接口基本上都是表示可以排序的接口
    2. Iterator接口
      • Iterator接口的功能是从前向后输出,属于单向的输出
      • Iterator的主要功能就是完成迭代输出的操作.
      • 使用Iterator的时候最后不要删除数据
      • Iterator是一个接口,必须依靠Collection接口完成实例化
      • 示例:
      • public static void main(String args[]){
            List<String> all= new ArrayList<String>() ;    //
            all.add("hello") ;
            all.add("_") ;
            all.add("world") ;
            Iterator<String> iter = all.iterator() ;    // 为Iterator接口实例化
            while(iter.hasNext()){    // 判断是否有内容
                System.out.println(iter.next()) ;    // 输出内容
            }
        }
    3. ListIterator接口
      • ListIterator接口是Iterator的子接口
      • 定义:
      • public interface ListIterator<E> extends Iterator<E>
      • ListIterator可以进行增加(add())与替换(set())元素
      • 输出时要注意:必须先进行由前向后输出,才能进行由后向前输出.
      • 示例:
      • public static void main(String argsp[]){
            List<String> all = new ArrayList<String>() ;
            all.add("hello") ;
            all.add("_") ;
            all.add("world") ;
            ListIterator<String> iter = all.listIterator() ;
            System.out.print("由前向后输出:") ;
            while(iter.hasNext()){
                String str = iter.next() ;
                System.out.print(str + "、") ;
                iter.set("LI - " + str) ;    // 修改内容
            }
            System.out.print("
        由后向前输出:") ;
            iter.add("LXH");
            while(iter.hasPrevious()){
                String str = iter.previous() ;
                System.out.print(str + "、") ;
            }
        }
    4. Enumeration接口与foreach输出
      • foreach可以输出数组,同样也支持集合的输出操作.
      • 示例:
      • public static void main(String args[]){
            List<String> all = new ArrayList<String>() ;
            all.add("hello") ;
            all.add("_") ;
            all.add("world") ;
            for(String str:all){
                System.out.print(str + "、") ;
            }
        }
      • Enumeration输出一般都是直接操作Vector类完成,示例:
      • public static void main(String args[]){
            Vector<String> all = new Vector<String>() ;
            all.add("hello") ;
            all.add("_") ;
            all.add("world") ;
            Enumeration<String> enu = all.elements() ;
            while(enu.hasMoreElements()){    //判断是否有内容,hasNext()
                System.out.print(enu.nextElement() + "、") ;    // 输出元素:next()
            }
        }
    5. Map接口
      • 方法:
      • 1)public void clear()// 清空Map集合
        2)public boolean containsKey(Object Key) //判断指定的key是否存在
        3)public boolean containsValue(Object value) //判断指定的value是否存在
        4)public Set<Map Entry<K,V>> entrySet() //将Map对象变成为Set集合
        5)public boolean equals (Object o) //对象比较
        6)public v get(Object key) //根据key取得value
        7)public int hashCode() //返回哈希码
        8)public boolean isEmpty()// 判断集合是否为空
        9)public Set<K> keyset() //取得所有的key
        10)public V put(K key,V value)// 向集合中加入元素
        11)public void putAll(Map<? extends K,? extends V> t) //将一个Map集合中的内容加入到另一个Map
        12)public V remove (Object key) //根据key删除value
        13)public int size() //取出集合的长度
        14)public Collection<V> values() //取出全部的value
      • Map接口的常用子类
        • 1)HashMap:无序存放,是新的操作类,key不允许重复
          • A.示例1:输出key的值:
          • public static void main(String args[]){
                Map<String,String> map = null; // 声明Map对象,其中key和value的类型为String
                map = new HashMap<String,String>() ;
                map.put("mldn","www.mldn.cn") ; // 增加内容
                map.put("zhinangtuan","www.zhinangtuan.net.cn") ; // 增加内容
                map.put("mldnjava","www.mldnjava.cn") ; // 增加内容
                Set<String> keys = map.keySet() ; // 得到全部的key
                Iterator<String> iter = keys.iterator() ;
                while(iter.hasNext()){
                    String str = iter.next() ;
                    System.out.print(str + "、") ;
                }
            }
          • B.示例2:输出value的值
          • public static void main(String args[]){
                Map<String,String> map = null; // 声明Map对象,其中key和value的类型为String
                map = new HashMap<String,String>() ;
                map.put("mldn","www.mldn.cn") ; // 增加内容
                map.put("zhinangtuan","www.zhinangtuan.net.cn") ; // 增加内容
                map.put("mldnjava","www.mldnjava.cn") ; // 增加内容
                Collection<String> values = map.values() ; // 得到全部的value
                Iterator<String> iter = values.iterator() ;
                while(iter.hasNext()){
                    String str = iter.next() ;
                    System.out.print(str + "、") ;
                }
            }
        • 2)Hashtable:无序存放,是旧的操作类,key不允许重复
        • 3)TreeMap: 可以排序的Map集合,按集合中的key排序,key不允许重复
        • public static void main(String args[]){
              Map<String,String> map = null; // 声明Map对象,其中key和value的类型为String
              map = new TreeMap<String,String>() ;
              map.put("A、mldn","www.mldn.cn") ; // 增加内容
              map.put("C、zhinangtuan","www.zhinangtuan.net.cn") ; // 增加内容
              map.put("B、mldnjava","www.mldnjava.cn") ; // 增加内容
              Set<String> keys = map.keySet() ; // 得到全部的key
              Iterator<String> iter = keys.iterator() ;
              while(iter.hasNext()){
                  String str = iter.next() ;
                  System.out.println(str + " --> " + map.get(str)) ; // 取出内容
              }
          }
        • 4)WeakHashMap: 弱引用的Map集合,当集合中的某些内容不再使用时,可以清除无用的数据,可以使用gc进行回收
        • 5)IdentityHashMap:key可以重复的Map集合
      • Map接口输出:不能直接使用迭代输出(如:Iterator,foreach),Map每个位置存放的是一对值,而Iterator中每次只能找到一个值,要想使用迭代就必须按一下步骤完成:
        • 1)将Map的实例通过entrySet()方法变为Set接口对象
        • 2)通过Set接口实例为Iterator实例化
        • 3)通过Iterator迭代输出,每个内容都是Map.Entry的对象
        • 4)通过Map.Entry进行Keyvalue的分离
        • 5)示例1,一般输出:
        • public static void main(String args[]){
              Map<String,String> map = null; // 声明Map对象,其中key和value的类型为String
              map = new HashMap<String,String>() ;
              map.put("mldn","www.mldn.cn") ; // 增加内容
              map.put("zhinangtuan","www.zhinangtuan.net.cn") ; // 增加内容
              map.put("mldnjava","www.mldnjava.cn") ; // 增加内容
              Set<Map.Entry<String,String>> allSet = null ;
              allSet = map.entrySet() ;
              Iterator<Map.Entry<String,String>> iter = null ;
              iter = allSet.iterator() ;
              while(iter.hasNext()){
                  Map.Entry<String,String> me = iter.next() ;
                  System.out.println(me.getKey() + " --> " + me.getValue()) ;
              }
              for(Map.Entry<String,String> me:map.entrySet()){
                  System.out.println(me.getKey() + " --> " + me.getValue()) ;
              }
          }
        • 6)示例2,用对象做Key查询:
        • class Person{
              private String name ;
              private int age ;
              public Person(String name,int age){
                  this.name = name ;
                  this.age = age ;
              }
              public String toString(){
                  return "姓名:" + this.name + ";年龄:" + this.age ;
              }
              public boolean equals(Object obj){
                  if(this==obj){
                      return true ;
                  }
                  if(!(obj instanceof Person)){
                      return false ;
                  }
                  Person p = (Person)obj ;
                  if(this.name.equals(p.name)&&this.age==p.age){
                      return true ;
                  }else{
                      return false ;
                  }
              }
              public int hashCode(){
                  return this.name.hashCode() * this.age ;
              }
          };
          public class HashMapDemo08{
              public static void main(String args[]){
                  Map<Person,String> map = null ;
                  map = new HashMap<Person,String>() ;
                  //map = new IdentityHashMap<Person,String>() ; //用IdentityHashMap是可以使Map类重复的
                  map.put(new Person("张三",30),"zhangsan"); // 增加内容
                  System.out.println(map.get(new Person("张三",30))) ;
              }
          };
    6. SortedMap接口:此接口可以排序
    7. 1)public Comparator<? super K> comparator()// 返回比较器对象
      2)public K firstKey() // 返回第一个元素的key
      3)public SortedMap<K,V> headMap(K toKey) //返回小于等于指定key的部分集合
      4)public K lastKey() //返回最后一个元素的key
      5)public SortedMap<K,V> subMap(K fromKey, K toKey) //返回指定Key范围的集合
      6)public SortedMap<K,V> tailMap(K fromKey) //返回大于指定key的部分集合
      • 示例:
      1. public static void main(String args[]){
            SortedMap<String,String> map = null ;
            map = new TreeMap<String,String>() ; // 通过子类实例化接口对象
            map.put("D、jiangker","http://www.jiangker.com/") ;
            map.put("A、mldn","www.mldn.cn") ;
            map.put("C、zhinangtuan","www.zhinangtuan.net.cn") ;
            map.put("B、mldnjava","www.mldnjava.cn") ;
            System.out.print("第一个元素的内容的key:" + map.firstKey()) ;
            System.out.println(":对应的值:" + map.get(map.firstKey())) ;
            System.out.print("最后一个元素的内容的key:" + map.lastKey()) ;
            System.out.println(":对应的值:" + map.get(map.lastKey())) ;
            System.out.println("返回小于指定范围的集合:") ;
            for(Map.Entry<String,String> me:map.headMap("B、mldnjava").entrySet()){
              System.out.println("	|- " + me.getKey() + " --> " + me.getValue()) ;
            }
            System.out.println("返回大于指定范围的集合:") ;
            for(Map.Entry<String,String> me:map.tailMap("B、mldnjava").entrySet()){
              System.out.println("	|- " + me.getKey() + " --> " + me.getValue()) ;
          }
            System.out.println("部分集合:") ;
            for(Map.Entry<String,String> me:map.subMap("A、mldn","C、zhinangtuan").entrySet()){
              System.out.println("	|- " + me.getKey() + " --> " + me.getValue()) ;
            }
        }
    8. Collections类
      • 方法:
      • 1)public static final List EMPTY_LIST //返回一个空的List集合
        2)public static final Set EMPTY_SET //返回空的Set集合
        3)public static final Map EMPTY_MAP// 返回空的Map集合
        4)public static <T> boolean addALL(Collection<? super T> c,T…a)// 为集合添加内容
        5)public static <T extends Object & Comparable<? super T>>T max(Collection<? extends T> coll)// 找到最大的内容,比较器排序
        6)public static <T extends Object & Comparable<? super T>>T min(Collection<? extends T> coll) //找到最小的内容,比较器排序
        7)public static <T> boolean replaceAll(List<T> list, T oldVal,T newVal) //用新的内容替换集合的指定内容
        8)public static void reverse(List<?> list) //集合反转
        9)public static <T> int binarySearch(List<? extends Comparable<? super T>> list,T key) //查找集合中的指定内容
        10)public static final<T> List<T> emptyList() //返回一个空的List集合
        11)public static final<K,V> Map<K,V> emptyMap()// 返回一个空的Map集合
        12)public static final<K,V> Map<K,V> emptySet() //返回一个空的Set集合
        13)public static <T extends Comparable<? super T>> void sort(List<T> list) //集合排序操作,根据Comparable接口进行排序
        14)public static void swap(List<?> list, int i, int j) //交换指定位置的元素
      • 示例1,加入内容:
      • public static void main(String args[]){
            List<String> all = new ArrayList<String>() ; // 返回空的 List集合
            Collections.addAll(all,"MLDN","LXH","mldnjava") ;
            Collections.reverse(all) ; // 内容反转
            Iterator<String> iter = all.iterator() ;
            while(iter.hasNext()){
                System.out.print(iter.next() + "、") ;
            }
        }
      • 示例2,检索与替换
      • public static void main(String args[]){
            List<String> all = new ArrayList<String>() ; // 返回空的 List集合
            Collections.addAll(all,"MLDN","LXH","mldnjava") ;
            int point = Collections.binarySearch(all,"LXH") ; // 检索数据
            System.out.println("检索结果:" + point) ;
            if(Collections.replaceAll(all,"LXH","李兴华")){// 替换内容
                System.out.println("内容替换成功!") ;
            }
            System.out.print("替换之后的结果:") ;
            System.out.print(all) ;
        }
      • 示例3,交换内容:
      • public static void main(String args[]){
            List<String> all = new ArrayList<String>() ; // 返回空的 List集合
            Collections.addAll(all,"1、MLDN","2、LXH","3、mldnjava") ;
            System.out.println("交换之前的集合:" + all) ;
            Collections.swap(all,0,2) ;
            System.out.println("交换之后的集合:" + all) ;
        }
    9. Stack类
      • 栈:先进后出的功能,在java中使用stack类进行栈的操作,Stack类是Vector的子类,定义:public class Stack<E> extends Vector<E>
      • 示例:
      • public static void main(String args[]){
            Stack<String> s = new Stack<String>() ;
            s.push("A") ; // 入栈
            s.push("B") ; // 入栈
            s.push("C") ; // 入栈
            System.out.print(s.pop() + "、") ;
            System.out.print(s.pop() + "、") ;
            System.out.println(s.pop() + "、") ;
            System.out.println(s.pop()) ;
        }
    10. Properties属性类
      • 在类集中提供了一个专门的Properties类,以完成属性的操作.定义:
      • public class Properties extends Hashtable<Object,Object>
      • 方法:
      • 1)public Object setProperty(String key, String value)// 设置属性
        2)public String getProperty(String key) //得到属性
        3)public String getProperty(String key,StringdefaultValue) //得到属性和值
        4)public void store (OutputStream out, String comments) throws IOException //将属性保存到文件中
        5)public void Load(InputStream inStream) throws IOException //读取文件中的属性
      • 示例1,读取和设置:
      • public static void main(String args[]){
            Properties pro = new Properties() ; // 创建Properties对象
            pro.setProperty("BJ","BeiJing") ; // 设置属性
            pro.setProperty("TJ","TianJin") ;
            pro.setProperty("NJ","NanJing") ;
            System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;
            System.out.println("2、SC属性不存在:" + pro.getProperty("SC")) ;
            System.out.println("3、SC属性不存在,同时设置显示的默认值:" + pro.getProperty("SC","没有发现")) ;
        }
      • 示例2,保存到文件:
      • public static void main(String args[]){
            Properties pro = new Properties() ; // 创建Properties对象
            pro.setProperty("BJ","BeiJing") ; // 设置属性
            pro.setProperty("TJ","TianJin") ;
            pro.setProperty("NJ","NanJing") ;
            File file = new File("D:" + File.separator + "area.properteis") ; // 指定要操作的文件
            try{
                pro.store(new FileOutputStream(file),"Area Info") ; // 保存属性到普通文件
            }catch(FileNotFoundException e){
                e.printStackTrace() ;
            }catch(IOException e){
                e.printStackTrace() ;
            }
        }
      • 示例3,读取文件:
      • public static void main(String args[]){
            Properties pro = new Properties() ; // 创建Properties对象
            File file = new File("D:" + File.separator + "area.properteis") ; // 指定要操作的文件
            try{
                pro.load(new FileInputStream(file)) ; // 读取属性文件
            }catch(FileNotFoundException e){
                e.printStackTrace() ;
            }catch(IOException e){
                e.printStackTrace() ;
            }
            System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;
            System.out.println("2、SH属性存在:" + pro.getProperty("SH")) ;
        }
      • 示例4,保存到XML文件:
      • public static void main(String args[]){
            Properties pro = new Properties() ; // 创建Properties对象
            pro.setProperty("BJ","BeiJing") ; // 设置属性
            pro.setProperty("TJ","TianJin") ;
            pro.setProperty("NJ","NanJing") ;
            File file = new File("D:" + File.separator + "area.xml") ; // 指定要操作的文件
            try{
                pro.storeToXML(new FileOutputStream(file),"Area Info") ; // 保存属性到普通文件
            }catch(FileNotFoundException e){
                e.printStackTrace() ;
            }catch(IOException e){
                e.printStackTrace() ;
            }
        }
      • 示例5,读取XML文件:
      • public static void main(String args[]){
            Properties pro = new Properties() ; // 创建Properties对象
            File file = new File("D:" + File.separator + "area.xml") ; // 指定要操作的文件
            try{
                pro.loadFromXML(new FileInputStream(file)) ; // 读取属性文件
            }catch(FileNotFoundException e){
                e.printStackTrace() ;
            }catch(IOException e){
                e.printStackTrace() ;
            }
            System.out.println("1、BJ属性存在:" + pro.getProperty("BJ")) ;
        }

    13.java类集枚举(Enum)

    1. 枚举可以限制取值范围,定义:
      • [public] enum 枚举类型名称{
            枚举对象1,枚举对象2,…,枚举对象n;
        }
    2. 使用 “枚举对象名称.values()”的形式取得全部内容用foreach输出:
      • for(Color c:Color.values()){    // 输出枚举中的全部内容
            System.out.println(c) ;
        }
    3. Enum类:enum关键字可以定义一个枚举,实际上是默认的继承Enum类
      • 1)定义: public abstract class Enum<E extends Enum<E>>extends Objectimplements Comparable<E>, Serializable
      • 2)方法:
      • A.protected Enum(String name, int ordinal)// 接收枚举的名称和枚举的常量创建枚举对象
        B.protected final Object cloue() throws CloneNotSupportedException// 克隆枚举对象
        C.public final int compareTo(E o) //对象比较
        D.public final boolean equals(Object other) //比较两个枚举对象
        E.public final int hashCode() //返回枚举常量的哈希码
        F.public final String name()// 返回此枚举的名称
        G.public final int ordinal() //返回枚举常量的序数
        H.public static <T extends Enum<T>>T valueOf(Class<T> enumType,String name)// 返回带指定名称的指定枚举类型的枚举常量
      • 3)示例1,通过构造方法设置属性
      • enum Color{
            RED("红色"),GREEN("绿色"),BLUE("兰色") ;
            private Color(String name){
                this.setName(name) ;
            }
            private String name ;    // 定义name属性
            public void setName(String name){
                this.name = name ;
            }
            public String getName(){
                return this.name ;
            }
        }
        public class ConstructorEnum{
            public static void main(String args[]){
                for(Color c:Color.values()){
                    System.out.println(c.ordinal() + " --> " + c.name()+"(" + c.getName() + ")") ;
                }
            }
        };
      • 4)示例2,通过setter得到属性:
      • enum Color{
            RED,GREEN,BLUE ;
            private String name ;    // 定义name属性
            public void setName(String name){
            switch(this){    // 判断操作的是那个枚举对象
                case RED:{
                    if("红色".equals(name)){
                        this.name = name ;    // 允许设置名字
                    }else{
                        System.out.println("设置内容错误。") ;
                    }
                break ;
                }
                case GREEN:{
                    if("绿色".equals(name)){
                        this.name = name ;    // 允许设置名字
                    }else{
                        System.out.println("设置内容错误。") ;
                    }
                    break ;
                }
                case BLUE:{
                    if("蓝色".equals(name)){
                        this.name = name ;    // 允许设置名字
                    }else{
                        System.out.println("设置内容错误。") ;
                    }
                    break ;
                }
            }
            this.name = name ;
            }
            public String getName(){
                return this.name ;
            }
        }
        public class ValueOfEnum{
            public static void main(String args[]){
                Color c = Color.valueOf(Color.class,"BLUE") ;    // 得到兰色
                //Color c = Color.BLUE ;    // 得到兰色
                c.setName("兰色") ;    // 名字错误
                c.setName("蓝色") ;    // 名字正确
                System.out.println(c.getName()) ;
            }
        };                    
      • 5)示例3,枚举排序:
      • enum Color{
            RED,GREEN,BLUE ;
        }
        public class ComparableEnum{
            public static void main(String args[]){
                Set<Color> t = new TreeSet<Color>() ;    // 设置类型
                t.add(Color.GREEN) ;    // 加入绿色
                t.add(Color.RED) ;    // 加入红色
                t.add(Color.BLUE) ;    // 加入蓝色
                Iterator<Color> iter = t.iterator() ;
                while(iter.hasNext()){
                    System.out.print(iter.next() + "、") ;
                }
            }
        };
    4. 类集多Enum的支持:
      • 1)EnumMap类
        • A.定义: public class EnumMap<K extends Enum<K>,V>extends AbstractMap<K,V>implements Serializable, Cloneable
        • B.示例:
        • enum Color{
              RED , GREEN , BLUE ;
          }
          public class EnumMapDemo{
              public static void main(String args[]){
                  Map<Color,String> desc = null ;    // 定义Map对象,同时指定类型
                  desc = new EnumMap<Color,String>(Color.class) ;    // 实例化    EnumMap对象
                  desc.put(Color.RED,"红色") ;
                  desc.put(Color.GREEN,"绿色") ;
                  desc.put(Color.BLUE,"蓝色") ;
                  System.out.println("====== 输出全部的内容 ======") ;
                  for(Color c:Color.values()){
                      System.out.println(c.name() + " --> " + desc.get(c)) ;
                  }
                  System.out.println("====== 输出全部的键值 ======") ;
                  for(Color c:desc.keySet()){
                      System.out.print(c.name() + "、") ;
                  }
                  System.out.println() ;
                  System.out.println("====== 输出全部的内容 ======") ;
                  for(String s:desc.values()){
                      System.out.print(s + "、") ;
                  }
              }
          };
      • 2)EnumSet类
        • A.EnumSet类是Set接口的子类,所以里面的内容是无法重复的,在使用EnumSet的时候是不能直接使用new为其进行实例化的,使用静态方法完成.
        • B.示例:
        • import java.util.EnumSet ;
          enum Color{
              RED , GREEN , BLUE ;
          }
          public class EnumSetDemo05{
              public static void main(String args[]){
                  EnumSet<Color> esOld = null ;    // 声明一个EnumSet对象
                  EnumSet<Color> esNew = null ;
                  System.out.println("======== EnumSet.copyOf(Color.class) =====") ;
                  esOld = EnumSet.noneOf(Color.class) ;    // 将枚举的全部类型设置到EnumSet对象之中
                  esOld.add(Color.RED) ;    // 增加内容
                  esOld.add(Color.GREEN) ;    // 增加内容
                  esNew = EnumSet.copyOf(esOld) ;    // 从已有的集合拷贝过来
                  print(esNew) ;
              }
              public static void print(EnumSet<Color> temp){    // 专门的输出操作
                  for(Color c:temp){    // 循环输出EnumSet中的内容
                      System.out.print(c + "、") ;
                  }
                  System.out.println() ;
              }
          };
    5. 枚举类型可以实现一个接口,但是实现接口的时候要求枚举中的每个对象都必须单独覆写好接口中的抽象方法.可以在枚举中定义抽象方法,但是要求枚举中的每个对象都分别实现此抽象方法.
    6. 示例:
    7. enum Color implements Print{
          RED{
              public String getColor(){
                  return "红色" ;
              }
          },GREEN{
              public String getColor(){
                  return "绿色" ;
              }
          },BLUE{
              public String getColor(){
                  return "蓝色" ;
              }
          } ;
          public abstract String getColor() ;
      }
      public class AbstractMethodEnum{
          public static void main(String args[]){
              for(Color c:Color.values()){
                  System.out.print(c.getColor() + "、") ;
              }
          }
      };


      Enum补充:http://www.cnblogs.com/yysbolg/p/6554269.html

    精品原创

  • 相关阅读:
    重装win7之后,wubi安装的ubuntu的启动菜单不见
    data_source.rb:182: TZInfo::DataSourceNotFound解决办法
    Gem::InstallerError:The 'json' native gem requires installed build tools
    去掉DL is deprecated, please use Fiddle警告信息
    ruby on rails安装(ubuntu 14.04)
    ruby on rails 安装(win8 64位)
    满城月季花开
    python中的zip()函数
    python学习之“序列”的理解
    二进制、十进制、八进制、十六进制的理解
  • 原文地址:https://www.cnblogs.com/yysbolg/p/6710415.html
Copyright © 2020-2023  润新知