Java Foundation --- Collection (Part 1)

Java Foundation - Collection (Part 1)

1. Collection class

  • The origin of the collection class: Objects are used to encapsulate unique data, and more objects need to be stored; if the number of objects is uncertain, a collection container is used for storage.

  • Collection features:

    1. A container for storing objects .

    2. The length of the collection is variable .

    3. Collections cannot store primitive data types.

  • Differences between array and collection classes:

    1. Although arrays can also store objects, the length is fixed; collections are variable in length.

    2. Arrays can store basic data types, and collections can only store objects.

  • The composition and classification of the collection framework:
    write picture description here

2. Collection interface

  • Common methods of Collection:

    1. Add to:

      1. boolean add(Object obj); add element.

      2. boolean addAll(Collection coll); Add all elements in the specified collection to this collection.

    2. delete:

      1. boolean remove(Object obj); removes the element.

      2. boolean removeAll(Collection coll); Removes elements from the specified collection that are also included in this collection.

      3. void clear(); removes all elements in the collection.

    3. judge:

      1. boolean contains(Object obj); Whether to contain an element.

      2. boolean containsAll(Collection coll); whether contains all elements in the specified collection,

      3. boolean isEmpty(); Determines whether there is an element in the collection.

    4. Obtain:

      1. int size(); returns the number of elements in this Collection.

      2. Iterator iterator(); Iterator: The Iterator interface is the public interface for all Collection containers to extract elements.

    5. other:

      1. boolean retainAll(Collection coll); Take the intersection.

      2. Object toArray(); Convert the collection to an array.

  • Example:
    • Code:
import java.util.*;
class CollectionDemo
{
    public static void main(String[] args) 
    {
        Collection coll =new ArrayList();
        show(coll);
        System.out.println("………………………………");
        Collection c1=new ArrayList();
        Collection c2=new ArrayList();
        show(c1,c2);
    }
    public static void show(Collection coll)
    {
        coll.add("abc1");
        coll.add("abc2");
        coll.add("abc3");
        System.out.println("coll="+coll);

        coll.remove("abc2");//移除集合中的元素
        System.out.println("coll="+coll);

        coll.clear();//清空集合
        System.out.println(coll.contains("abc1"));//判断集合中是否含有"abc1"元素
    }

    public static void show(Collection c1,Collection c2)
    {
        c1.add("abc1");
        c1.add("abc2");
        c1.add("abc3");
        c1.add("abc4");
        c2.add("abc5");
        c2.add("abc2");
        c2.add("abc7");
        System.out.println("c1="+c1);
        System.out.println("c2="+c2);

        c1.addAll(c2);//将集合c2中的元素都添加到c1中去
        System.out.println("c1="+c1);


        boolean b=c1.removeAll(c2);//将c1集合中所包含的c2集合元素全部去除
        System.out.println("b:"+b);

        boolean b1=c1.containsAll(c2);//判断c1集合是否包含c2集合所有的元素
        System.out.println("b1="+b1);

        boolean b2=c1.retainAll(c2);//取c1集合与c2集合的交集
        System.out.println("c1、c2的交集"+c1);
    }
}
  • output result
    write picture description here

3. List, Set

  • Collection

    • |–List: Ordered (the order of storage and retrieval is the same), elements have indexes (angular labels), and repeated elements are allowed.

    • |–Set: elements cannot be repeated, unordered

  • List

    • |–vector: The interior is an array data structure, which is synchronized. Additions and deletions, queries are very slow.

    • |–ArrayList: The internal is an array data structure, which is asynchronous. Instead of Vector, the query speed is very fast.

    • |–LinkedList: The internal is a linked list data structure, which is different; synchronous. Elements are added and removed very quickly.

  • Set

    • |–HashSet: The internal data structure is a hash table, which is different.

    • |–TreeSet: The elements in the Set collection can be sorted and are not synchronized.

  • Precautions:

    • In the iterator process, do not use the collection to operate the elements, it is prone to exceptions.

      • Solution: You can use ListIterator, a subinterface of the Iterator interface, to perform operations on elements during iteration.
  • Unique and common methods of List (there is one thing in common: they can all operate corner markers)

    1. Add to

      1. void add(index,element); Insert the specified element at the specified position

      2. void addAll(index,collection); Inserts all elements in the specified collection into the specified position in the list.

    2. delete

      1. Object remove(index); removes the element at the specified position.
    3. Revise

      1. Object set(index,element); Replace the element at the specified position on the list with the specified element.
    4. Obtain:

      1. Object get(index); Get the element at the specified position.

      2. int indexOf(object); returns the index of the first occurrence of the specified element in this list

      3. int lastIndexOf(object); Returns the index of the last occurrence of the specified element in this list.

      4. List subList(from,to); Get the sub-collection.

  • Example:

    • Code:
import java.util.ArrayList;
import java.util.List;
class ListDemo
{
    public static void main(String[] args) 
    {
        List list=new ArrayList();
        show(list);
    }
    public static void show(List list)
    {
        //在集合结尾添加元素
        list.add("abc1");
        list.add("abc2");
        list.add("abc3");
        System.out.println(list);
        //在集合指定位置插入元素
        list.add(1,"abc2");
        System.out.println(list);
        //去除集合中角标为2的元素
        System.out.println(list.remove(2));
        //修改集合中角标为2的元素
        System.out.println(list.set(2,"abc8"));
        //获取集合众角标为1的元素
        System.out.println(list.get(1));
        //获取子集合,含头不含为
        System.out.println(list.subList(1,2));
        System.out.println(list);
    }
}
  • Output result:
    write picture description here

四、ArrayList、LinkedList

  • ArrayList : For the common methods of ArrayList, see the methods of its parent class List.

  • LinkedList method (new method after jdk1.6 version) :

    1. Increase
      1. offerFirst(); // Insert the specified element at the beginning of this list.
      2. offerLast(); // Insert the specified element at the end of this list.
    2. delete
      1. pollFirst();//Get and remove the first element of this list; if this list is empty, return null.
      2. pollLast();//Gets and removes the last element of this list; returns null if this list is empty.
    3. read
      1. peekList(); // Gets but does not remove the first element of this list; returns null if this list is empty.
      2. peekLast(); // Gets but does not remove the last element of this list; returns null if this list is empty.
  • Example:
    • Code:
import java.util.*;
class LinkedListDemo
{
    public static void main(String[] args) 
    {
        LinkedList link =new LinkedList();

        link.offerFirst("abc1");
        link.offerFirst("abc2");
        link.offerFirst("abc3");
        link.offerFirst("abc4");

        System.out.println(link);

        System.out.println("获取的第一个元素:"+link.peekFirst());//获取容器的第一个元素,但不移除元素

        System.out.println("获取的最后一个元素:"+link.peekLast());//获取容器的最后一个元素,但不移除元素

        System.out.println("移除的第一个元素:"+link.pollFirst());//获取容器的第一个元素,并移除元素

        System.out.println("移除的最后一个元素:"+link.pollLast());//获取容器的最后一个元素,并移除元素

        while(!link.isEmpty())
        {       
            System.out.println(link.pollFirst());//若容器不为空,将元素从第一个开始依次获取并移除
        }
    }
}
  • Output result:
    write picture description here

五、HashSet、TreeSet

  • Common methods of Set: The methods in the Set interface are consistent with Collection

  • Features:

    • The elements of the Set collection are unordered.

    • Elements in a collection are unique.

1、HashSet

  • The basis for HashSet to determine whether the elements are the same:
    1. The judgment is whether the hash value of the two elements is the same. If they are the same, then judge whether the contents of the two objects are the same.
    2. Judging the hash value is the same, in fact, the judgment is the HashCode method of the object. To determine the same content, the equals method is used.

- Example:
- Code:

import java.util.*;
class Person
{
    private String name;
    private int age;
    Person()
    {}
    Person(String name,int age)
    {
        this.name=name;
        this.age=age;
    }
    public  void setName(String name)
    {
        this.name=name;
    }
    public  void setAge(int age)
    {
        this.age=age;
    }
    public String getName()
    {
        return this.name;
    }
    public int getAge()
    {
        return this.age;
    }
    //复写hashCode方法,先判断hashCode是否相等,若相等则判断元素内容是否相等
    public int hashCode()
    {
        return name.hashCode()+age*39;
    }
    //复写equals方法,判断对象内容是否相等
    public boolean equals(Object obj)
    {
        //若传入同一个对象,则直接返回true
        if(this==obj)
            return true;
        //若传入的不是Person类的对象,则抛出异常
        if(!(obj instanceof Person))
            throw new ClassCastException("类型错误");
        Person p=(Person)obj;
        return this.name.equals(p.name) && this.age==p.age;
    }
}

class HashSetTest1
{
    public static void main(String[] args) 
    {
        HashSet hs=new HashSet();

        hs.add(new Person("li1",10));
        hs.add(new Person("li2",20));
        //重复的元素
        hs.add(new Person("li1",10));
        hs.add(new Person("li3",30));
        hs.add(new Person("li4",40));

        Iterator it =hs.iterator();
            while (it.hasNext())
            {
                Person p=(Person)it.next();
                System.out.println(p.getName()+"…………"+p.getAge());
            }

    }
}
  • The result of the output:
    write picture description here

2、TreeSet

  • The way TreeSet judges the uniqueness of an element : it is based on whether the return result of the comparison method is 0. If it is 0, it means the same element and does not exist.

  • TreeSet sorts elements in two ways:

    1. To make the element itself have the comparison function, the element needs to implement the Comparable interface and override the compareTo method.

    2. Let the collection itself have the comparison function, define a class to implement the Comparator interface, and override the compare method.

  • Example (sort by means of a comparator):

    • code
    • Requirement: sort according to the length of the string
import java.util.*;
//创建一个根据字符串长度进行排序的比较器(从小到大排列)
class CompareByLen implements Comparator
{
    public int compare(Object o1,Object o2)
    {
        String s1=(String)o1;
        String s2=(String)o2;
        //若长度一样,则根据字符的自然顺序排列
        int num=s1.length()-s2.length();
        return num==0?s1.compareTo(s2):num;
    }
}
class  comparatorDemo
{
    public static void main(String[] args) 
    {
        //将比较器传入集合
        TreeSet hs=new TreeSet(new CompareByLen());
        hs.add("me");
        hs.add("you");
        hs.add("his");
        hs.add("they");
        //用迭代器将集合中的元素打印出来
        Iterator it =hs.iterator();
            while (it.hasNext())
            {
                System.out.println(it.next());
            }
    }
}

write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325519021&siteId=291194637