Java集合框架(一)-----Collection接口

一、集合框架的概述

1.集合、数组都是对多个数据进行存储操作的结构,简称java容器
说明:此时的存储指的是内存层面的存储,不涉及持久化的操作(.txt .jpg .avi 数据库等等)
2.1数组在存储多个数据方面的特点:
① 一旦初始化以后,其长度就固定了
② 数据一旦定义好,其元素的类型也就确定了,我们也只能操作指定的类型数据了。
③ 比如 String[] arr,int[] arr1,Object[] arr2

2.1数组在存储多个数据方面的确定:
① 一旦初始化以后,其长度就不可修改了
② 数组中提供的方法非常有限,对于增删改插入数据等操作,非常不便,并且效率不高。
③ 获取数组中的实际元素的个数的需求,数组没有现成的属性或者方法可以使用
④ 数组的特点:有序,可以重复,对于无序,不可重复的需求,不能满足

二、集合框架—主要使用

在这里插入图片描述

java集合可以分为Collection和Map两种体系

Collection接口:单列数据,定义了存取一个一个对象的集合

1.List:存储有序,可重复的数据 --“动态数组”

ArrayList、LinkedList、Vector

2.Set:存储无序,不可重复的集合,底层为链表

HashSet、LinkedHashSet、TreeSet

Map接口:双列数据,保存具有映射关系"key-value对"的数据

HashMap、LinkedHashMap、TreeMap、Hashtable、Properties

三、Collection接口中的方法使用

自定义一个类(Person ),用于数据的测试

public class Person implements Comparable {
   public String name;
   public  int age;

   public String getName() {
       return name;
   }

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

   public int getAge() {
       return age;
   }

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

   @Override
   public String toString() {
       return "Person{" +
               "name='" + name + '\'' +
               ", age=" + age +
               '}';
   }

   public Person() {
   }

   public Person(String name, int age) {
       this.name = name;
       this.age = age;
   }
   //重写equals()方法,比较判断contains()中的比较问题

   @Override
   public boolean equals(Object o) {
       if (this == o) return true;
       if (o == null || getClass() != o.getClass()) return false;

       Person person = (Person) o;

       if (age != person.age) return false;
       return name != null ? name.equals(person.name) : person.name == null;
   }

   @Override
   public int hashCode() {
       int result = name != null ? name.hashCode() : 0;
       result = 31 * result + age;
       return result;
   }
   //按照姓名从小到大排列,年龄从小到大排序
   @Override
   public int compareTo(Object o) {
      if (o instanceof Person){
          Person person = (Person)o;
//           return  this.name.compareTo(person.name);
          int compare = this.name.compareTo(person.name);
          if (compare !=0){
              return compare;
          }else {
              return  Integer.compare(this.age,person.age);
          }
      }else {
          throw  new RuntimeException("输入的类型不匹配!");
      }
   }
}
Collection的常用方法列举

1.add(Object o); 讲元素o添加到集合coll中
2.size():获取添加的元素个数
3.addAll(Collection coll):将coll集合中的元素添加到当前集合中
4.clear():清空集合元素
5.isEmpty():判断当前集合是否为空
6.contains(Object o):判断当前集合是否包含obj
7.containsAll(Collection coll1):判断形参coll1中的所有元素是否在当前集合中
8.remove(Object o):从当前集合中删除obj元素
9.removeAll(Collection coll1):从当前集合中移除coll1中的所有元素
10.retainAll():获取当前集合和coll1集合的交集,并返回当前集合(保留一样的,去掉不一样的)
11.equals(Object o):要想返回true,现需要当前集合和方法的形参集合的元素相同(判断当前集合和形参Object的值是否相同)
12.hashCode()返回当前对象的哈希值
13.集合 —>数组:toArray()
14.iterator():返回Iterator接口的实例,用于遍历集合元素

  Collection coll = new ArrayList();

        //1.add(Object o); 讲元素o添加到集合coll中
        coll.add("aa");
        coll.add("bb");
        coll.add("cc");
        coll.add(123);//自动装箱
        coll.add(new Date());

        //2.size():获取添加的元素个数
        System.out.println(coll.size());//4

        Collection coll1 = new ArrayList();

        //3.addAll(Collection coll):将coll集合中的元素添加到当前集合中
        coll1.add(456);
        coll1.add("abc");
        coll.addAll(coll1);

        System.out.println(coll.size());//6


        //4.clear():清空集合元素
        coll.clear();//0

        //5.isEmpty():判断当前集合是否为空
        System.out.println(coll.isEmpty());//true
        
	@Test
    public void test(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom",20));
        Person p = new Person("Jerry",20);
        coll.add(p);
        //6.contains(Object o):判断当前集合是否包含obj
        //我们会在判断时调用obj所在对象类的equals()
        boolean contains = coll.contains(123);
        System.out.println(contains);
        System.out.println(coll.contains(p));//true
        System.out.println(coll.contains(new Person("Jerry",20)));//true

        //7.containsAll(Collection coll1):判断形参coll1中的所有元素是否在当前集合中
        Collection coll1 = Arrays.asList(123,456,789);
        System.out.println(coll.containsAll(coll1));
    }
     @Test
    public void test1(){
        //8.remove(Object o):从当前集合中删除obj元素
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom",20));

        coll.remove(123);
        System.out.println(coll);//[456, Tom, false, Person{name='Tom', age=20}]

        boolean remove = coll.remove(1234);
        System.out.println(remove);//false

        boolean tom = coll.remove(new Person("Tom", 20));
        System.out.println(tom);//true

        //9.removeAll(Collection coll1):从当前集合中移除coll1中的所有元素
        Collection coll1 = Arrays.asList(123,456);
        coll.removeAll(coll1);
        System.out.println(coll);//[Tom, false, Person{name='Tom', age=20}]
    }
     @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom",20));

        //10.retainAll():获取当前集合和coll1集合的交集,并返回当前集合(保留一样的,去掉不一样的)
       // Collection  coll1 = Arrays.asList(123,456,789);
       // coll.retainAll(coll1);
        //System.out.println(coll);//[123, 456]

        //11.equals(Object o):要想返回true,现需要当前集合和方法的形参集合的元素相同
        // (判断当前集合和形参Object的值是否相同)
        Collection coll1 = new ArrayList();
        coll1.add(123);
        coll1.add(456);
        coll1.add(new String("Tom"));
        coll1.add(false);
        coll1.add(new Person("Tom",20));
        //若现在集合中的元素交换位置的话,就会是false,因为(new ArrayList())的要考虑顺序问题
        System.out.println(coll.equals(coll1));//true

    }
     @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom",20));

        //12.hashCode()返回当前对象的哈希值
        System.out.println(coll.hashCode());//239446066

        //13.集合 --->数组:toArray()
        Object[] arr = coll.toArray();
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+"\t");//123	456	Tom	false	Person{name='Tom', age=20}
        }

        //拓展:数据 ---> 集合:调用ArrayList的静态方法asList()
        List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"});
        System.out.println(list);//[AA, BB, CC]
        //将其识别为一个元素,不是两个
        List ints = Arrays.asList(new int[]{123, 456, 789});
        System.out.println(ints);//[[I@4f2410ac] .size()的话,值为1

        //14.iterator():返回Iterator接口的实例,用于遍历集合元素 ,在IteratorTest使用
    }

四、迭代器的使用

1.集合元素的遍历操作,使用迭代器Iterator接口(是设计模式中的一种),主要用于遍历Collection集合中元素

在这里插入图片描述
迭代器模式:提供一种方法访问一个容器(container)对象中的各个元素,而又不暴露该对象的内部细节
这种模式就是为容器而生,容器里面有很多对象(集合,数组)
1.集合的方法 hasNext() 和 next()
2.集合中对象每次调用iterator()方法都会得到一个全新的迭代器对象,
默认下标都在第一个元素之前
3.内部定义了remove(),可以在遍历的时候,删除集合中当元素,此方法不同于集合直接调用remove()


public class IteratorTest {

    @Test
    public void test() {
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom", 20));

        Iterator iterator = coll.iterator();
        //方式一:取决于集合中有多少个元素
        //next():①指针下移 ②将下移以后集合位置上的元素返回
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
//        System.out.println(iterator.next());
        //抛异常,没有下一个元素了  java.util.NoSuchElementException
//        System.out.println(iterator.next());

        //方式二:不推荐
//        for (int i = 0; i < coll.size(); i++) {
//            System.out.println(iterator.next());
//        }
        //方式三:推荐
        //hasNext():判断是否还有下一个元素,有true,没有false
        while (iterator.hasNext()){
            //next():①指针下移 ②将下移以后集合位置上的元素返回
            System.out.print(iterator.next()+"\t");//123	456	Tom	false	Person{name='Tom', age=20}
        }
    }
    @Test
    public void test1(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom", 20));

        //错误发生一:判断为空时,输出的是下一条的数据信息
//        Iterator iterator = coll.iterator();
//        while (iterator.next() !=null){
//            System.out.println(iterator.next());//456 false
//        }
        //错误发生二:coll.iterator()会返回新的iterator对象,在hasNext就一直是第一个元素
        while (coll.iterator().hasNext()){
            System.out.println(coll.iterator().next());//123循环输出
        }
    }

    //测试remove()
    @Test
    public void test2(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom", 20));

        Iterator iterator = coll.iterator();
        //删除集合中的数据
        while (iterator.hasNext()){
            //如何还没有调用next(),就删除会抛异常,因为现在集合为空,没有执行next,指针不在集合中
            // iterator.remove();
            Object next = iterator.next();
            if ("Tom".equals(next)){
                iterator.remove();
            }
        }
        //需要重新获取一个新的对象
         iterator = coll.iterator();
        //重新遍历集合
        while (iterator.hasNext()){
            System.out.print(iterator.next() +"\t");//123	456	false	Person{name='Tom', age=20}
        }
    }
}

五、增强for循环

jdk5.0新增foreach循环,用于遍历集合,数组

public class ForTest {

    @Test
    public void test(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);
        coll.add(new Person("Tom", 20));

        //for(集合元素类型 局部遍历 :集合对象)
        for (Object obj : coll){//内部调用任然是迭代器
            System.out.println(obj);
        }
    }
    //练习题
    @Test
    public void test1(){
        String[] str = new String[]{"MM","MM","MM"};
        //普通的for循环,改变String的值
//        for (int i = 0; i < str.length; i++) {
//            str[i] = "GG";
//        }
        //增强for循环,新增变量String s:不会改变原来的值,重新赋了一个值
        for (String s :str){
            s = "GG";
        }

        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
    }
}
发布了19 篇原创文章 · 获赞 0 · 访问量 484

猜你喜欢

转载自blog.csdn.net/weixin_43244120/article/details/105496021