JAVA 之"集合"

本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/anlisten/archive/2009/11/21/4846878.aspx

 

1、集合其实可以看成为数组的扩展,它与数组的不同之处在于:

       《1》 一个数组只允许存储一种类型的数据,而一个集合可以存储任一种对象类型数据;

               简单的说一个集合类似一个 Object[] 数组,因为一切类的基类都为Object类,

                       所以一切类都可以隐式转换为Object类,然后存储到Object类型的数组中。

       《2》数组的大小为固定的,而集合的大小却可以根据数据的多少来自动增加或减小;

 

       《3》可以通过 泛型 <类型>  来使集合转换为类似数组的集合,如:

               List<String> list=new ArrayList<String>();

               该集合中就只能存储String类型的数据。

     

 2、集合中的接口与类,以及他们的关系: 

       《1》Collection接口:

 

             Collection(接口)
                        |


                /                 \
    List(接口)               Set(接口)
           |                             |
      /        \                      /          \

ArrayList  LinkedList  HashSet  SortedSet
                                     |
                                  TreeSet

 

 

 

        《2》Map接口

 

                   Map(接口)


              /           |            \
 SortedMap   Hashtable   HashMap
              |           |
    TreeMap      Properties

 

 

3、各种集合类的特征:

      《1》list  有序排序的集合,可以有重复元素;

      《2》ArrayList :顺序表存储,用于多 查询 的数据存储;
      《3》LinkedList:链表存储,用于多 插入、删除 的数据存储;

      《4》set   无序排列的集合,不能有重复元素;

      《5》Map :  非线性排列,键值对存储(键唯一),<key>=<value>;
      《6》Hashtable:  键与值都不允许存 NULL值,线程安全;
      《7》HashMap:   键与值都允许存放 NULL 值,线程不安全。

 

4、集合中的 迭代器 Iterator :

       Iterator 用于迭代获取一个集合中的数据,类似于数组中for迭代:

      《1》数组中:有arr数组:

       for(int i=0;i<arr.length;i++){

           System.out.println(arr[i]);

       }

      《2》集合中:有list集合:

        Iterator it=list.iterator();
        while(it.hasNext()){
           System.out.println(it.next());
       }

 

       如果在arr与list中存储的数据一致,则《1》、《2》打印的效果一致;

       注意:在Iterator 中调用it.next()相当与在for中同时执行了arr[i] 和 i++;

                 所以当我们要打印一个user对象的name和age时,我们不能执行:

                 Iterator it=list.iterator();
                 while(it.hasNext()){
                   System.out.println(it.next().getName());

                   System.out.println(it.next().getAge());
                 }

                 正确代码为:

                 Iterator it=list.iterator();
                 while(it.hasNext()){

                   User user=it.next();
                   System.out.println(user.getName());

                   System.out.println(user.getAge());
                 }

 

 5、集合中元素的排序(这里只讲客户化排序即自定义排序):

      《1》定义排序规则:

            (1) 创建一个排序规则类实现 Comparator接口;

            (2) 在该类中重写compare方法,定义排序规则;

      《2》将集合排序:

            (1) List集合的排序:Collections.sort(list, c);

                  c为 排序规则类 的对象;

                 List  先插入数据,再按定义的规则排序;

            (2)TreeSet集合排序:Set set=new TreeSet(c) ;

                  c为 排序规则类 的对象;

                 TreeSet 先定义排序规则,再按规则插入数据;

 6、set 中去重复数据:

  虽然set不允许插入重复值,但由于set对对象是否重复是通过调用该对象中的equals

  方法来判断的,所以我们要重写该类中的equals方法(参见:equals详解),

  同时重写hashCode方法,使两个相同属性的对象返回相同的hashCode;

 

     注意:由于TreeSet是先定义排序再插入数据的,所以当按排序规则排序后发现两个数据      

             的顺序相同,则将两个数据看成是重复的数据,则不插入,所以TreeSet中可以通

             过排序规则来去重复数据。 

 7、实例代码:

 《1》List

view plaincopy to clipboardprint?
package day1;  
 
public class Student {  
    private String name;  
    private String sex;  
    private int age;  
    private int score;  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public String getSex() {  
        return sex;  
    }  
    public void setSex(String sex) {  
        this.sex = sex;  
    }  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
    public int getScore() {  
        return score;  
    }  
    public void setScore(int score) {  
        this.score = score;  
    }  
    public Student(String name, String sex, int age, int score) {  
        super();  
        this.name = name;  
        this.sex = sex;  
        this.age = age;  
        this.score = score;  
    }  
    public Student() {  
        super();  
    }  
    @Override 
    public String toString() {  
        return "name:"+this.name+"  age:"+this.age+"  sex:"+this.sex+"  score:"+this.score;  
    }  
      

package day1;

public class Student {
 private String name;
 private String sex;
 private int age;
 private int score;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSex() {
  return sex;
 }
 public void setSex(String sex) {
  this.sex = sex;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public int getScore() {
  return score;
 }
 public void setScore(int score) {
  this.score = score;
 }
 public Student(String name, String sex, int age, int score) {
  super();
  this.name = name;
  this.sex = sex;
  this.age = age;
  this.score = score;
 }
 public Student() {
  super();
 }
 @Override
 public String toString() {
  return "name:"+this.name+"  age:"+this.age+"  sex:"+this.sex+"  score:"+this.score;
 }
 
}
      

view plaincopy to clipboardprint?
package day1;  
 
import java.util.Comparator;  
 
public class StuComparator implements Comparator{  
 
    /** 
     * 实现接口中的方法,用于定义排序规则 
     * 定义规则为:先按成绩降序排序,如果成绩相同则按年龄升序排序 
     */ 
    public int compare(Object o1, Object o2) {  
        Student stu1=(Student)o1;  
        Student stu2=(Student)o2;  
        int age=stu1.getAge()-stu2.getAge();  
        int score=stu2.getScore()-stu1.getScore();  
        if(score!=0){  
            return score;  
        }else{  
            return age;  
        }  
          
    }  
 

package day1;

import java.util.Comparator;

public class StuComparator implements Comparator{

 /**
  * 实现接口中的方法,用于定义排序规则
  * 定义规则为:先按成绩降序排序,如果成绩相同则按年龄升序排序
  */
 public int compare(Object o1, Object o2) {
  Student stu1=(Student)o1;
  Student stu2=(Student)o2;
  int age=stu1.getAge()-stu2.getAge();
  int score=stu2.getScore()-stu1.getScore();
  if(score!=0){
   return score;
  }else{
   return age;
  }
  
 }

}
 

view plaincopy to clipboardprint?
package day1;  
 
import java.util.ArrayList;  
 
import java.util.Collections;  
import java.util.Iterator;  
import java.util.List;  
 
public class ListTest {  
    public static void main(String[] args) {  
        Student stu1=new Student("张三","男",16,88);  
        Student stu2=new Student("李四","男",19,100);  
        Student stu3=new Student("王五","男",19,76);  
        Student stu4=new Student("林想","女",16,98);  
        Student stu5=new Student("赵说","男",15,98);  
        List list=new ArrayList();   
        StuComparator c=new StuComparator();  
        list.add(stu1);  
        list.add(stu2);  
        list.add(stu3);  
        list.add(stu4);  
        list.add(stu5);  
        System.out.println("----------------for-----------------");  
        for(int i=0;i<list.size();i++){  
            System.out.println(list.get(i));  
        }  
        System.out.println("--------------Iterator--------------");  
        Iterator it=list.iterator();  
        while(it.hasNext()){  
            System.out.println(it.next());  
        }  
        Collections.sort(list, c);  
        System.out.println("----------------sort----------------");  
        Iterator it1=list.iterator();  
        while(it1.hasNext()){  
            System.out.println(it1.next());  
        }  
    }  

package day1;

import java.util.ArrayList;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class ListTest {
 public static void main(String[] args) {
  Student stu1=new Student("张三","男",16,88);
  Student stu2=new Student("李四","男",19,100);
  Student stu3=new Student("王五","男",19,76);
  Student stu4=new Student("林想","女",16,98);
  Student stu5=new Student("赵说","男",15,98);
  List list=new ArrayList();
  StuComparator c=new StuComparator();
  list.add(stu1);
  list.add(stu2);
  list.add(stu3);
  list.add(stu4);
  list.add(stu5);
  System.out.println("----------------for-----------------");
  for(int i=0;i<list.size();i++){
   System.out.println(list.get(i));
  }
  System.out.println("--------------Iterator--------------");
  Iterator it=list.iterator();
  while(it.hasNext()){
   System.out.println(it.next());
  }
  Collections.sort(list, c);
  System.out.println("----------------sort----------------");
  Iterator it1=list.iterator();
  while(it1.hasNext()){
   System.out.println(it1.next());
  }
 }
}
 

 

《2》Set

view plaincopy to clipboardprint?
package day2;  
 
 
public class Student {  
    private String name;  
    private String sex;  
    private int age;  
    private int score;  
 
    public String getName() {  
        return name;  
    }  
 
    public void setName(String name) {  
        this.name = name;  
    }  
 
    public String getSex() {  
        return sex;  
    }  
 
    public void setSex(String sex) {  
        this.sex = sex;  
    }  
 
    public int getAge() {  
        return age;  
    }  
 
    public void setAge(int age) {  
        this.age = age;  
    }  
 
    public int getScore() {  
        return score;  
    }  
 
    public void setScore(int score) {  
        this.score = score;  
    }  
 
    public Student(String name, String sex, int age, int score) {  
        super();  
        this.name = name;  
        this.sex = sex;  
        this.age = age;  
        this.score = score;  
    }  
 
    public Student() {  
        super();  
    }  
 
    @Override 
    public String toString() {  
        return "name:" + this.name + "  age:" + this.age + "  sex:" + this.sex  
                + "  score:" + this.score;  
    }  
 
 
    //TreeSet中可以不覆盖hashCode()方法,即可通过 排序比较 时返回的值来确认是否重复  
    
//  @Override  
//  public boolean equals(Object obj) {  
//      if((obj instanceof Student)){  
//          Student other=(Student) obj;  
//          if(this.name.equals(other.getName())) {  
//              return true;  
//          }  
//      }  
//      return false;  
//        
//  }  
 
      
    //treeset中也可以不覆盖hashCode()方法,即可通过 排序比较 时返回的值来确认是否重复  
    
//  @Override  
//  public int hashCode() {  
//      int result;  
//      result=(name==null?0:name.hashCode());  
//      return result;  
//  }  
 

package day2;


public class Student {
 private String name;
 private String sex;
 private int age;
 private int score;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSex() {
  return sex;
 }

 public void setSex(String sex) {
  this.sex = sex;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public int getScore() {
  return score;
 }

 public void setScore(int score) {
  this.score = score;
 }

 public Student(String name, String sex, int age, int score) {
  super();
  this.name = name;
  this.sex = sex;
  this.age = age;
  this.score = score;
 }

 public Student() {
  super();
 }

 @Override
 public String toString() {
  return "name:" + this.name + "  age:" + this.age + "  sex:" + this.sex
    + "  score:" + this.score;
 }


    //TreeSet中可以不覆盖hashCode()方法,即可通过 排序比较 时返回的值来确认是否重复
 
// @Override
// public boolean equals(Object obj) {
//  if((obj instanceof Student)){
//   Student other=(Student) obj;
//   if(this.name.equals(other.getName())) {
//    return true;
//   }
//  }
//  return false;
//  
// }

 
 //treeset中也可以不覆盖hashCode()方法,即可通过 排序比较 时返回的值来确认是否重复
 
// @Override
// public int hashCode() {
//  int result;
//  result=(name==null?0:name.hashCode());
//  return result;
// }

}
 

 view plaincopy to clipboardprint?
package day2;  
 
import java.util.Comparator;  
/** 
 * 实现一个Comparator接口,用于定义一个排序规则 
 * @author yuyihua 
 * 
 */ 
public class StuComparator implements Comparator{  
 
    /** 
     * 实现接口中的方法,用于定义排序规则 
     * 定义规则为:先按成绩降序排序,如果成绩相同则按年龄升序排序,最后按姓名排列 
     * 该排序也能把分数,年龄,姓名都相同的两个对象,当成重复对象。 
     */ 
    public int compare(Object o1, Object o2) {  
        Student stu1=(Student)o1;  
        Student stu2=(Student)o2;  
        int age=stu1.getAge()-stu2.getAge();  
        int score=stu2.getScore()-stu1.getScore();  
        int name=stu1.getName().compareTo(stu2.getName());  
        if(score!=0){  
            return score;  
        }else{  
            if(age!=0){  
                return age;  
            }  
            else{  
                return name;  
            }  
        }  
          
    }  
 

package day2;

import java.util.Comparator;
/**
 * 实现一个Comparator接口,用于定义一个排序规则
 * @author yuyihua
 *
 */
public class StuComparator implements Comparator{

 /**
  * 实现接口中的方法,用于定义排序规则
  * 定义规则为:先按成绩降序排序,如果成绩相同则按年龄升序排序,最后按姓名排列
  * 该排序也能把分数,年龄,姓名都相同的两个对象,当成重复对象。
  */
 public int compare(Object o1, Object o2) {
  Student stu1=(Student)o1;
  Student stu2=(Student)o2;
  int age=stu1.getAge()-stu2.getAge();
  int score=stu2.getScore()-stu1.getScore();
  int name=stu1.getName().compareTo(stu2.getName());
  if(score!=0){
   return score;
  }else{
   if(age!=0){
    return age;
   }
   else{
    return name;
   }
  }
  
 }

}
 

view plaincopy to clipboardprint?
package day2;  
 
import java.util.Iterator;  
import java.util.Set;  
import java.util.TreeSet;  
 
public class SetTest {  
    public static void main(String[] args) {  
        StuComparator c=new StuComparator();  
        //创建一个带有客户化(自定义规则)排序的TreeSet  
        Set set=new TreeSet(c) ;   
        Student stu1=new Student("张三","男",16,88);  
        Student stu2=new Student("李四","男",19,100);  
        Student stu3=new Student("王五","男",19,76);  
        Student stu4=new Student("林想","女",16,98);  
        Student stu5=new Student("赵说","男",15,99);     
        Student stu6=new Student("赵飞","男",15,99);     
        set.add(stu1);  
        set.add(stu2);  
        set.add(stu3);  
        set.add(stu4);  
        set.add(stu5);  
        set.add(stu6);  
        Iterator it=set.iterator();  
        while(it.hasNext()){  
            System.out.println(it.next());  
        }  
 
    }  

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值