Java collection framework (1)-Collection interface

1. Overview of the collection framework

1. Collections and arrays are structures that perform storage operations on multiple data, referred to as java container
description: storage at this time refers to storage at the memory level, and does not involve persistent operations (.txt.jpg.avi database, etc.) )
2.1 The characteristics of the array in storing multiple data:
① Once initialized, its length is fixed
② Once the data is defined, the type of its element is determined, and we can only operate on the specified type of data.
③ For example String [] arr, int [] arr1, Object [] arr2

2.1 The determination of the array in storing multiple data:
① Once initialized, its length cannot be modified.
② The methods provided in the array are very limited. It is very inconvenient and inefficient for operations such as adding, deleting, modifying, and inserting data.
③ The need to obtain the actual number of elements in the array, the array does not have ready-made attributes or methods can be used
④ The characteristics of the array: ordered, repeatable, for unordered, non-repeatable requirements, can not meet

Second, the collection framework-mainly used

Insert picture description here

Java collection can be divided into two systems: Collection and Map

Collection interface: a single column of data, which defines access to a collection of objects

1.List: store ordered, repeatable data-"dynamic array"

ArrayList、LinkedList、Vector

2.Set: store unordered, non-repeatable collection, the bottom is a linked list

HashSet、LinkedHashSet、TreeSet

Map interface: double-column data, save data with mapping relationship "key-value pair"

HashMap、LinkedHashMap、TreeMap、Hashtable、Properties

Three, the use of methods in the Collection interface

Customize a class (Person) for data testing

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("输入的类型不匹配!");
      }
   }
}
List of common methods of Collection

1.add (Object o); Talk about the element o added to the collection coll
2.size (): Get the number of added elements
3.addAll (Collection coll): Add the elements in the coll collection to the current collection
4.clear (): Clear collection elements
5.isEmpty (): Determine whether the current collection is empty
6.contains (Object o): Determine whether the current collection contains obj
7.containsAll (Collection coll1): Determine whether all elements in the formal parameter coll1 are in the current collection
8.remove (Object o): delete obj elements from the current collection
9.removeAll (collection coll1): removed from the current set of all elements coll1 in
10.retainAll (): get the current collection and a collection of coll1 Intersect, and return the current collection (retain the same, remove the different)
11.equals (Object o): To return true, it is necessary that the elements of the formal collection of the current collection and the method are the same (judging the current collection and the formal parameter Object Whether the values ​​are the same)
12. hashCode () returns the hash value of the current object
13. Collection—> Array: toArray ()
14.iterator (): returns an instance of the Iterator interface, used to traverse the collection elements

  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使用
    }

Four, the use of iterators

1. The traversal operation of collection elements, using the Iterator interface (it is a kind of design pattern), mainly used to traverse the elements in the Collection collection

Insert picture description here
Iterator mode: Provide a method to access each element in a container object without exposing the internal details of the object.
This mode is for the container. There are many objects (collections, arrays) in the container
1. Collection methods hasNext () and next ()
2. Each time an iterator () method is called on an object in the collection, a new iterator object is obtained. The
default subscripts are before the first element.
3. Remove () is defined internally. You can delete the elements in the collection during the traversal. This method is different from calling remove () directly on the collection.


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}
        }
    }
}

Five, enhance the for loop

jdk5.0 adds a new foreach loop for traversing collections and arrays

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]);
        }
    }
}
Published 19 original articles · praised 0 · visits 484

Guess you like

Origin blog.csdn.net/weixin_43244120/article/details/105496021