java集合小结(2)

来源:互联网 发布:网络教育拿学位证书 编辑:程序博客网 时间:2024/06/06 13:23



1. Set

        Set是Collection的子接口;

      Set中不允许出现重复元素;

      用equals方法判断加入放入元素是否相等;

 1.1 HashSet

                 (1)不能保证存入的元素有序

             (2)不是线程安全的

             (3)可以添加null

             (4)如果两个对象的equals( )方法返回true,则hashCode()方法也应该相等

              

  1.2  LinkedHashSet

                  ( 1)LinkedHashSet为HashSet类的子类

             (2)用过链表维护元素的顺序,使元素按添加顺序排序

             (3)不允许出现相同元素,可以添加null

package com.exception;import java.util.HashSet;import java.util.LinkedHashSet;import java.util.Set;/** * 1.Set是Collection接口的子接口 * 2.Set 中不允许存放相同的元素,判断元素相同的标准的两个对象各自调 * 用equals()方法 * 3.hashSet * 3.1基本特征: * 1)不能保证元素的排列顺序 * 2)HashSet 不是线程安全的 * 3)集合元素可以使 null * 4)如果两个对象通过 equals() 方法返回 true,这两个对象的 hashCode 值也应该相同      *4.LinkedHashSet   *4.1 LinkedHashSet 是 HashSet 的子类   *4.2使用链表维护维护元素的顺序,是元素看起来一插入顺序存放的   *4.3LinkedHashSet不允许元素重复,允许放入null          * */public class TestSet {public static void main(String[] args) { //Set hashset= new HashSet(); Set  hashset= new LinkedHashSet();hashset.add(null);System.out.println(hashset.size());hashset.add(new People("AA", 12));hashset.add(new People("BB", 13));for(Object obj: hashset){System.out.println(obj);}System.out.println(hashset.size());}}


 

1.3  TreeSet

            (1)使用TreeSet()无参构造方法创建TreeSet对象,放入的对象必须实现Comparable接口,所以不能

                      添加 null

            (2)不能添加不同类的对象,否则会发生类型转换异常

             (3)两个对象调用Comparable的compareTo(Object o)比较大小,并进行升序排列,添加元素时需要对                       equals( )重写,应该保证equals( )返回值和compareTo()返回值一致,否则在插入元素时导致插 入  失   败

              (4)定制排序:在创建TreeSet对象的时候传入Comparator接口实现类对象,要求两个对象的equals方法返回值和compare方法返回值一致

<span style="font-size:18px;">package com.exception;import java.util.Comparator;import java.util.Set;import java.util.TreeSet;public class TestTreeSet {/** * TreeSet:  * 1. 如果使用 TreeSet() 无参数的构造器创建一个 TreeSet 对象, 则要求放入其中的元素的类必须实现 Comparable 接口 *    所以, 在其中不能放入 null 元素 * 2. 必须放入同样类的对象. 否则可能会发生类型转换异常.   * 3. 两个对象通过 Comparable 接口 compareTo(Object obj) 方法的返回值来比较大小, 并进行升序排列 * 4. 当需要把一个对象放入 TreeSet 中,重写该对象对应的 equals() 方法时, *    应保证该方法与 compareTo(Object obj) 方法有一致的结果 *     * 5. 定制排序: 创建 TreeSet 对象时, 传入 Comparator 接口的实现类.  *    要求: Comparator 接口的 compare 方法的返回值和 两个元素的 equals() 方法具有一致的返回值    * */public static void main(String[] args) {Set set= new TreeSet();//set.add(new People());//  set.add(null);//set.add("a");//set.add(123);set.add(new Student("AA",90));set.add(new Student("BB", 100));set.add(new Student("CC", 92));set.add(new Student("DD", 76));set.add(new Student("EE", 22));System.out.println(set.size());for(Object obj :set){System.out.println(obj);}Comparator  comparator =new Comparator () {@Overridepublic int compare(Object  o1, Object o2) { if(o1 instanceof People&& o2 instanceof People) { People p1= (People)o1; People p2 =(People)o2; return p1.getAge()-p2.getAge(); } else  throw new ClassCastException("不能转化为人类");    }     }; TreeSet  t1 =new TreeSet (comparator) ;           t1.add(new People("DD",45 ));         t1.add(new People("CC",56 ));         t1.add(new People("EE",33 ));         t1.add(new People("AA",12 ));         t1.add(new People("BB",34 ));         t1.add(new People("FF",22 ));            for(Object o: t1){      System.out.println(o);      }     }}</span>

2.  List

          List中的元素可重复,且有序,通过插入顺序确定元素的索引

2.1 ArrayList

         (1)元素访问方法:

                   通过通过迭代器访问;

                   通过for循环

                   增强for循环

         (2)其他方法:

             void add(int index, Object ele)
             boolean addAll(int index, Collection eles)
              Object get(int index)
             int indexOf(Object obj)
              int lastIndexOf(Object obj)
              Object remove(int index)
              Object set(int index, Object ele)
             

package com.exception;import java.lang.reflect.Array;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.ListIterator;public class TestArrayList {  public static void main(String[] args) {  ArrayList a =new ArrayList ();  a.add(new People("AA", 30));  a.add(new People("BB", 35));  a.add(new People("CC", 23));  a.add(new People("WW", 12));  a.add(new People("DD", 15));  a.add(new People("EE", 40));//  Iterator  iterator =a.iterator();//  while(iterator.hasNext())//  {//  System.out.println(iterator.next());//  }//  //}//  for(Object o:a)//  {//  System.out.println(o);//  }//使用for循环遍历,用list的get(int)方法//  for(int i=0;i<a.size();i++)//  {//  System.out.println(a.get(i));//  }//  //  void add(int index, Object ele)//      boolean addAll(int index, Collection eles)//      Object get(int index)//      int indexOf(Object obj)//      int lastIndexOf(Object obj)//      Object remove(int index)//      Object set(int index, Object ele)//      List subList(int fromIndex, int toIndex)//        a.add(2,new People("XX",34) );  a.add(5,new People("XX",34) );  System.out.println(a.indexOf(new People("XX",34)));  ListIterator listIterator =a.listIterator();while(listIterator.hasNext()){System.out.println(listIterator.next());}    System.out.println(a.indexOf(new People("XX",34)));  System.out.println(a. lastIndexOf( new People("XX",34) )); a.set(3, new People("XX",33));  for(int i=0;i<a.size();i++)  {  System.out.println(a.get(i));  }List list =a.subList(2, 5) ;System.out.println(); for(int i=0;i<list.size();i++)  {  System.out.println(list.get(i));  }  }    }


 3. Map

存放具有映射关系的数据,存放两组值,key,value;

key和value可以是任何的引用类型;

key和value存在单项一一对应关系;

3.1   HashMap

(1)用过HashMap来定义HashSet,HashMap 中的键为HashSet中的元素

(2)遍历:

得到键的集合keySet();

得到值得集合values();

得到键值对集合entrySet();


3.2TreeMap

(1)对TreeSet元素进行定义,TreeMap的键为TreeSet中的元素

 (2)可以按照键值进行定制排序,定义TreeMap时需传入Comparator实现类对象

package com.exception;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Collection;import java.util.Comparator;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Properties;import java.util.Set;import java.util.TreeMap;public class TestMap {/** * Map * 1. Map 用于保存具有映射关系的数据,因此 Map 集合里保存着两组值,一组值用于保存 Map 里的 Key,另外一组用于保存 Map 里的 Value * 2. Map 中的 key 和  value 都可以是任何引用类型的数据 * 3. Map 中的 Key 不允许重复,即同一个 Map 对象的任何两个 Key 通过 equals 方法比较中返回 false * 4. Key 和 Value 之间存在单向一对一关系,即通过指定的 Key 总能找到唯一的,确定的 Value。 *  * 5. HashMap 定义了 HashSet: HashMap 的键为 HashSet 里边的元素.  * @throws IOException  * @throws FileNotFoundException  * */public static void main(String[] args) throws FileNotFoundException, IOException {Map<String,Object>map =new HashMap<String,Object>();//向Map中添加元素:put(key,value);map.put("AA", new People("AA",23));map.put("BB", new People("BB",25));map.put("CC", new People("CC",34));map.put("DD", new People("DD",44));map.put("EE", new People("EE",34));map.put("FF", new People("FF",39));//从Map 中取出元素:    //2.1 得到键的集合:keySet()//Set keySet=map.keySet();//for(Object key: keySet){//Object value =map.get(key);//System.out.println(key+":"+value);//    //2.2直接得到value集合:Collection collection =map.values();    for(Object obj:collection)    {    System.out.println(obj);    }    //取出元素   map.remove("AA");  //2.3 得到键值对的集合:    for(Map.Entry<String, Object> entry:map.entrySet()){    String key=entry.getKey();    Object obj=entry.getValue();    System.out.println(key+":"+obj);        }      //工具类方法://size()    System.out.println(map.size());//contains()    System.out.println(map.containsKey("AA"));   //定义比较器    Comparator comparator =new Comparator () {@Overridepublic int compare(Object arg0, Object arg1) { People p1=(People)arg0; People p2=(People)arg1; return -p1.getAge()+p2.getAge();}        }; TreeMap treeMap=new TreeMap (comparator);  treeMap.put(new People("AA",45),"AA" ); treeMap.put(new People("BB",67),"BB" ); treeMap.put(new People("EE",32),"EE" ); treeMap.put(new People("FF",23),"FF" ); treeMap.put(new People("GG",36),"GG" ); treeMap.put(new People("JJ",28),"JJ" );     Set keySet=treeMap.keySet();for(Object  key: keySet){System.out.println(key+":"+treeMap.get(key));}/** * properties * *///1创建一个properties对象Properties properties=new  Properties();//2.使用IO流加载properties文件properties.load(new FileInputStream("jdbc.properties"));;//3.得到对应的属性String url=properties.getProperty("url");System.out.println(url);}}

4. Properties---访问属性文件,读取配置信息 

读取步骤:

(1)创建Properties对象

(2)通过IO流加载properties文件

(3)读取属性值

 

/** * properties * *///1创建一个properties对象Properties properties=new  Properties();//2.使用IO流加载properties文件properties.load(new FileInputStream("jdbc.properties"));;//3.得到对应的属性String url=properties.getProperty("url");

5.Collections----用于操作集合的工具类

(1)sort( )方法可以进行排序,需要传入Comparator接口实现类对象

(2)synchronizedXXX()获取线程安全的集合

(3)enumeration()获取Enumeration对象,通过hasMoreElements(),nextElement()进行遍历

<span style="font-size:14px;">package com.exception;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Enumeration;import java.util.List;/** * Collections是操作集合的工具类 *  * */public class TestCollections {public static void main(String[] args) {   List list =new ArrayList();   list.add(new People("AA", 32));   list.add(new People("BB", 33));   list.add(new People("CC", 18));   list.add(new People("CC", 18));   list.add(new People("EE", 16));      Collections.sort(list, new Comparator () {@Overridepublic int compare(Object o1, Object o2) { People p1 =(People)o1; People p2 =(People)o2; return p1.getAge()-p2.getAge();}});   for(Object obj:list){   System.out.println(obj);   }   //使用synchronizedList()获取线程安全的集合。    Collections.synchronizedList(new ArrayList());    System.out.println();    //enumeration对象遍历:hasMoreElements(),nextElement()    Enumeration  enumeration =Collections.enumeration(list);    while(enumeration.hasMoreElements()){      Object  obj=enumeration.nextElement();      System.out.println(obj);    }}}</span>


0 0
原创粉丝点击