List,Set和Map的介绍和使用

        一. 集合   
            数组的长度是固定的,在许多应用场合,一组数据的数目是不固定的,比如一个单位的员工数目是变化的,有老的员工跳槽,也有新的员工进来。单位的客户是变化的,有老的客户流失,也有新的客户签单。
            为了使程序能方便地存储和操纵数目不固定的一组数据,JDK类库提供了Java集合,所有Java集合类都位于java.util包中。
            与Java数组不同,Java集合中不能存放基本类型数据,而只能存放 对象的引用。出于表达上的便利,通常把“集合中的对象的引用”简称为“集合中的对象“。

            Java中集合主要分为三种类型:

    . List:存储: 有序的(放入的先后的次序), 可重复的
            访问:可以for循环,foreach循环,iterator迭代器 迭代。
    . Set :存储:无序,不可重复
           访问:可以foreach循环,iterator迭代器 迭代
    . Map :存储:存储的是一对一对的映射 ”key=value“,key值 是无序,不重复的。value值可重复
           访问:可以map中key值转为为set存储,然后迭代这个set,用map.get(key)获取value
                也可以 转换为entry对象 用迭代器迭代,也可以直接使用values()方法获取全部的值,返回collection对象

            1. Collection和Iterator接口
        Set和List接口继承了Collection接口
               在Collection接口中声明了适用于Set和List的通用方法:

               boolean add(Object o)          : 向集合中加入一个对象的引用;
               void clear()                              : 删除集合中的所有对象引用,即不再持有这些对象的引用;
               boolean contains(Object o)  : 判断在集合中是否持有特定对象的引用;
               boolean isEmpty()                  : 判断集合是否为空;
                Iterator iterator()                      : 返回一个Iterator对象,可用它来遍历集合中的元素;
               boolean remove(Object o)    : 从集合中删除一个对象的引用;
               int size()                                    : 返回集合中元素的数目;
               Object[] toArray()                     : 返回一个数组,该数组包含集合中的所有元素;
        
        Iterator接口中的定义的方法可以帮我们去遍历集合中的元素。

               Iterator接口隐藏底层集合的数据结构,向客户程序提供了遍历各种类型的集合的统一方法。

        Iterator接口中声明方法:

               hasNext()                      : 判断集合中的元素是否遍历完毕,如没有,就返回true;
               next()                             : 返回下一个元素;
               //remove()                     : 从集合中删除上一个由next()方法返回的元素;
               通过下面程序实践上面的方法:
           
   import java.util.*;
               public class Visitor {
                      public static void print(Collection c) {
                             Iterator it = c.iterator();
                             while(it.hasNext()) {
                                    Object element = it.next();
                                    System.out.println(element);
                             }
                      }

                      public static void main(String args[]) {
                             Set set = new HashSet();
                             set.add("Tom");
                             set.add("Mary");
                             set.add("Jack");
                             print(set);

                             List list = new ArrayList();
                             list.add("Linda");
                             list.add("Mary");
                             list.add("Rose");
                             print(list);

                             Map map = new HashMap();
                             map.put("M","男");
                             map.put("F","女");
                             print(map.entrySet());
                     }
               }

           I

            2. Set
               最简单的一种集合,集合中的对象无序、不能重复。

主要实现类包括:

               . HashSet      : 按照哈希算法来存取集合中的对象,存取速度比较快;
               . LinkedHashSet: HashSet子类,不仅实现Hash算法,还实现链表数据结构,链表数据结构能提高插入和删除元素的性能;
               . TreeSet      : 实现SortedSet接口,具有排序功能;
  一般用法:
               Set集合中存放的是对象的引用,并且没有重复对象。

package sample;
import java.util.*;
public class Hashset
{
  public static void main(String[] args)
  {
     Set set=new HashSet();
     String s1=new String("Hello");
     String s2=s1;//使得s1和s2有相同的地址
     String s3=new String("World");
     set.add(s1);
     set.add(s2);
     set.add(s3);
     System.out.println(set.size());
  }
}
运行结果如下所示:(注表示警告内容),从结果可以看出,输出的大小为2,表示set集合不能够添加重复的数


           当一个新的对象加入到Set集合中时,Set的add方法是如何判断这个对象是否已经存在于集合中的呢?它遍历既存对象,通过equals方法比较新对象和既存对象是否有相等的。      
        boolean isExist = false;
               Iterator it = set.iterator();
               while(it.hasNext()) {
                     String oldStr = it.next();
                     if(newStr.equals(oldStr)) {
                            isExists = true;
                            break;
                     }
               }
               1) HashSet              
                  按照哈希算法来存取集合中的对象,存取速度比较快。当向集合中加入一个对象时,HashSet会调用对象的hashCode()方法来获得哈希码,然后根据这个哈希码进一步计算出对象在集合中的存放位置。
                  在Object类中定义了hashCode()方法和equals()方法,Object类的equals()方法按照内存地址比较对象是否相等,因此如果object.equals(object2)为true, 则表明object1变量和object2变量实际上引用同一个对象,那么object1和object2的哈希码也肯定相同。

                  为了保证HashSet能正常工作, 要求当两个对象用equals()方法比较的结果为true时,它们的哈希码也相等。如果用户定义的Customer类覆盖了Object类的equals()方法,但是没有覆盖Object类的hashCode()方法,就会导致当 customer1.equals(customer2)为true时,而customer1和customer2的哈希码不一定一样,这会使HashSet无法正常工作。(先调用对象的hashCode()方法比较,如果是true再调用equals方法比较,如果还是true再认为俩个对象是同一个0)

如下所示代码,我们先进行创建Customer类

package sample;
public class Customer
{
  	public String name;
	public int age;
	public Customer(String name,int age)
	{
	 this.name=name;
	 this.age=age;
	}
	public boolean equals(Object o)
	{
	  if(this==o)return true;
	  if(!(o instanceof Customer))return false;
	  Customer other=(Customer)o;
	  if(this.name.equals(other.name)&&this.age==other.age)
	  return true;
	  else return false;
	}
}
以下程序向HashSet中加入两个Customer对象。

package sample;
import java.util.*;
public class HashTest
{
  public static void main(String[] args)
  {
     Set set=new HashSet();
     Customer customer1=new Customer("Tom",15);
     Customer customer2=new Customer("Tom",15);
     set.add(customer1);
     set.add(customer2);
     System.out.println(set.size());
  }
}

结果如下图所示:


                出现以上原因在于customer1和customer2的哈希码不一样,因此为两个customer对象计算出不同的位置,于是把它们放到集合中的不同的地方(也就是上面所说的,用户定义的Customer类覆盖了Object类的equals()方法,但是没有覆盖Object类的hashCode()方法,就会导致当 customer1.equals(customer2)为true时,而customer1和customer2的哈希码不一定一样,这会使HashSet无法正常工作。)。

                  应加入以下hashCode()方法·{即,在Customer 类中加入以下代码,进行对hashCode()函数进行重写}:                 
public int hashCode() {
                         return this.age;
                  }

重写hashCode()函数之后,我们运行后能够看到我们想要的结果(即正确的结果,因为我们输入的是相同的数据,只不过是地址不同而已):


            2) TreeSet

                 TreeSet实现了SortedSet接口,能够对集合中的对象进行排序。当TreeSet向集合中加入一个对象时,会把它插入到有序的对象序列中。那么TreeSet是如何对对象进行排序的呢?TreeSet支持两种排序方式:自然排序和客户化排序。默认情况下TreeSet采用的是自然排序方式:
                  a. 自然排序
                     在JDK类库中, 有一部分类实现了Comparable接口,如Integer、Double和String等。Comparable接口有一个compareTo(Object o)方法,它返回整数类型。对于x.comapreTo(y), 如
                     返回0,      表明   x和y相等
                     返回值大于0, 表明   x>y
                     返回值小于0, 表明   x<y
                    **即:想表示出x比y大,让x.comapreTo(y)返回一个大于0的数字即可
                     TreeSet调用对象的compareTo()方法比较集合中对象的大小,然后进行【升序】排序,这种排序方式称为自然排序。
                    ------------------------------------------------------------------------------------------------
                     JDK类库中实现了Comparable接口的一些类的排序方式:
                     Byte, Short, Integer, Long, Double, Float     :         按数字大小排序;
                     Character                                     :         按字符的Unicode值的数字大小排序;
                     String                                        :         按字符串中字符的Unicode值排序;
                     ------------------------------------------------------------------------------------------------
                     使用自然排序, TreeSet中只能加入相同类型对象,且这些对象必须实现了Comparable接口。否则会抛出ClassCastException异常。
                     当修改了对象的属性后, TreeSet不会重新排序。最适合TreeSet排序的是不可变类(它们的对象的属性不能修改)。
                  b. 客户化排序                

                     除了自然排序外, TreeSet还支持客户化排序。

                     java.util.Comparator接口提供了具体的排序方法, 它有一个compare(Object x, Object y)方法,用于比较两个对象的大小,

当compare(x,y):

                     返回0,       表明   x和y相等
                     返回值大于0, 表明   x>y
                     返回值小于0, 表明   x<y

                     如果希望TreeSet按照Customer对象的name属性进行降序排列,可以先创建一个实现Comparator接口的类

首先实现Customer.java类,代码如下所示:

package sample;
public class Customer
{
  	public String name;
	public int age;
	public Customer(String name,int age)
	{
	 this.name=name;
	 this.age=age;
	}
 //注释掉前一种使用方式
 /*public boolean equals(Object o)
	{
	  if(this==o)return true;
	  if(!(o instanceof Customer))return false;
	  Customer other=(Customer)o;
	  if(this.name.equals(other.name)&&this.age==other.age)
	  return true;
	  else return false;
	}
	public int hashCode()
	{
            return this.age;
        }*/
	public String getName()
	{
	  return name;
	}
	public int getAge()
	{
	   return age;
	}
}
接着创建 CustomerComparator, 参见:

package sample;
import java.util.*;
public class CustomerComparator implements Comparator
{
	public int compare(Object o1,Object o2)
	{
	   Customer c1=(Customer)o1;
	   Customer c2=(Customer)o2;
	   if(c1.getName().compareTo(c2.getName())>0)return -1;
	   if(c1.getName().compareTo(c2.getName())<0) return 1;
	   return 0;
	}
	public static void main(String[] agrs)
	{
	   Set set=new TreeSet(new CustomerComparator());
	   Customer customer1=new Customer("Tom",15);
	   Customer customer2=new Customer("Jack",16);
	   Customer customer3=new Customer("suwu150",23);
	   set.add(customer1);
	   set.add(customer2);
	   set.add(customer3);

	   Iterator it=set.iterator();
	   while(it.hasNext())
	   {
	     Customer customer=(Customer)it.next();
	     System.out.println(customer.getName()+" "+customer.getAge());
	   }
	}
}

                      打印输出结果如下所示:



            3. List
                主要特征是其元素以线性方式存储,集合中允许存放重复对象。
主要实现类包括:
               . ArrayList: 代表长度可变的数组。允许对元素进行快速的随机访问,但是向ArrayList中插入与删除元素的速度较慢;
               . LinkedList: 在实现中采用链表结构。对顺序访问进行了优化,向List中插入和删除元素的速度较快,随机访问速度则相对较慢。
               .Vector:   是线程安全的集合
               遍历方式:
               a. list.get(i);    //通过索引检索对象;
               b. Iterator it = list.iterator();
                    it.next();
如下所示程序:

package sample;
import java.util.*;//List,ArrayList
public class ListTest
{
	public static void main(String[] args)
	{
	  System.out.println("main:");
	  //create coll object
	  List l1=new ArrayList();//List不能创建对象,只能创建实现类
	  System.out.println(l1.size());
	  l1.add(123);//add()里边(5.0版本)以前是放对象的,现在可以直接放数字
	  l1.add("Hello");//表示向列表的尾部添加
	  l1.add("Hello");
	  l1.add("Hello");
//	  l1.remove(1);
	  System.out.println(l1.size());
	  System.out.println("输出");
	  Iterator iter=l1.iterator();
	  for(;iter.hasNext();)
	  {
	    System.out.println(iter.next());
	  }
	}
}
运行结果如下所示,从结果可以看出,在加入项目之后,List大小变为4,list中数据可以重复:

              

            4. Map
           HashMap  是线程不安全的集合。
           HashTable是线程安全的集合。

           TreeMap可以进行排序(对key进行排序)

注:Map中取值方式介绍Map中取值方式

               Map是一种把键对象和值对象进行映射的集合,它的每一个元素都包含一对键对象和值对象。向Map集合中加入元素时,必须提供一对键对象和值对象,从Map集合中检索元素时,只要给出键对象,就会返回对应的值对象。
               map.put("2", "Tuesday");
               map.put("3", "Wednsday");
               map.put("4", "Thursday");
               String day = map.get("2");    //day的值为"Tuesday"
               Map集合中的键对象不允许重复,如以相同的键对象加入多个值对象,第一次加入的值对象将被覆盖。
               对于值对象则没有唯一性的要求,可以将任意多个键对象映射到同一个值对象上。
               map.put("1", "Mon");
               map.put("1", "Monday");      //"1"此时对应"Monday"
               map.put("one", "Monday");    //"one"此时对应"Monday"
              Map有两种比较常见的实现:
               1) HashMap
                  按哈希算法来存取键对象,有很好的存取性能,为了保证HashMap能正常工作,和HashSet一样,要求当两个键对象通过equals()方法比较为true时,这两个键对象的hashCode()方法返回的哈希码也一样。
               2) TreeMap
                  实现了 SortedMap接口,能对键对象进行排序。和TreeSet一样,TreeMap也支持自然排序和客户化排序两种方式。(排序按照的是Map值中的键KEY值)                 
package sample;
import java.util.*;
public class Treemap
{
	public static void main(String[] args)
	{
	  Map map=new TreeMap();
	//添加不规则顺序的键
	  map.put("1","Monday");
	  map.put("3","Wednsday");
	  map.put("4","Thursday");
	  map.put("2","Tuesday");

	  Set keys=map.keySet();
	  Iterator it=keys.iterator();
	  while(it.hasNext())
	  {
	    String key=(String)it.next();
	    String value=(String)map.get(key);
	    System.out.println(key+" "+value);
	  }
	}
}
                 打印输出,由结果可以看出,TreeMap 为添加的内容进行了重新排序:

                 


以上就是集合的介绍
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

suwu150

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值