Java Road -- Day15(Collection class)

Keywords: Java JDK

2019-11-01-22:09:09

Catalog

1. Concept of collection

2. Common methods of collection collection

3.Iterator iterator

4. Enhance for

5. Common collection tools

The concept of Collection collection

● set: set is a container provided in java, which can be used to store multiple data.

Since sets and arrays are containers, what's the difference between them?

● the length of the array is fixed. The length of the set is variable.

● elements of the same type are stored in the array. Basic data type values can be stored. Collections store objects. And the types of objects can be inconsistent. In development, when there are many objects, the collection is used for storage.

Collection collection common methods

 1 package demosummary.collection;
 2 /*
 3    public boolean add(E e) :Adds the given object to the current collection.
 4   public void clear():Empty all elements in the collection.
 5   public boolean remove(e e);Delete the given object in the current collection.
 6   public boolean contains(E e) ;Determines whether the current collection contains the given object.
 7   public boolean isEmpty(): Determines whether the current set is empty.
 8   public int size(): Returns the number of elements in the collection.
 9   public object[] toArray(): Store the elements in the collection into an array.
10  */
11 import java.util.ArrayList;
12 import java.util.Collection;
13 
14 public class CollectionTest {
15     public static void main(String[] args) {
16 
17         Collection<String> str = new ArrayList<>();
18         /*
19             public boolean add(E e) :Add the given object to the current collection
20          */
21         boolean b = str.add("Zhang San");
22 //        System.out.println(b);//true
23         str.add("Li Si");
24         str.add("Wang Wu");
25         str.add("Money six");
26         str.add("Zhao Qi");
27 //        System.out.println(str);//[Zhang San, Li Si, Wang Wu, Money six, Zhao Qi]
28         /*
29             public boolean remove(e e);Delete the given object in the current collection
30          */
31 
32 //        boolean b1 = str.remove("Li Si");
33 //        System.out.println(b1);//true
34 //        System.out.println(str);//[Zhang San, Wang Wu, Money six, Zhao Qi]
35 
36         /*
37           public boolean contains(E e) ;Determine whether the current collection contains the given object
38          */
39         boolean b2 = str.contains("Sun Ba");
40         boolean b3 = str.contains("Zhao Qi");
41         System.out.println(b2);//false
42         System.out.println(b3);//true
43 
44         /*
45           public boolean isEmpty(): Determines whether the current set is empty.
46          */
47 
48         boolean b4 = str.isEmpty();
49         System.out.println(b4);//false
50 
51         /*
52           public int size(): Returns the number of elements in the collection
53          */
54         int b5 = str.size();
55         System.out.println(b5);//5
56 
57         /*
58           public object[] toArray(): Store the elements in the collection into an array
59          */
60         Object[] obj = str.toArray();
61         System.out.println(obj[0]);//Zhang San
62         for (Object o : obj) {
63             System.out.println(o);
64         }
65 
66         /*
67           public void clear():Empty all elements in the collection
68          */
69         str.clear();
70         System.out.println(str);//[]
71     }
72 }

Iterator iterator

Iterator interface

In program development, it is often necessary to traverse all elements in a collection. In response to this demand, JDK provides a special interface java.util. Iterator. Iterator interface is also a member of Java collection, but it is different from collection and Map interface. Collection interface and Map interface are mainly used to store elements, while iterator is mainly used to iterate (i.e. traverse) elements in collection, so iterator object is also called iterator.

Iteration:

This is the general way to get Collection collection elements. Before fetching elements, we should first judge whether there are elements in the set. If there are any, we should take them out, continue to judge, and if there are any, we should take them out again. Always take all the elements out of the Collection. The term for this extraction method is iteration.

Common methods of Iterator interface

public E next(): returns the next element of the iteration.
public boolean hasNext(): returns true if there are still elements that can be iterated

 1 package demosummary.collection;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 public class IteratorTest {
 8     public static void main(String[] args) {
 9         //Create a collection
10         Collection<String> obj = new ArrayList<>();
11         //Add elements to the collection
12         obj.add("DMAR");
13         obj.add("Prince");
14         obj.add("Debon");
15         obj.add("Blademaster");
16         //Using polymorphism to create implementation class objects
17         Iterator<String> iter = obj.iterator();
18         //Use while Loop to iterate over sets
19         while (iter.hasNext()){
20             String next = iter.next();//Using the principle of iterator
21             System.out.println(next);
22         }
23     }
24 }

Enhanced for

Enhanced for loop: the underlying layer also uses iterators. Using the format of for loop simplifies the writing of iterators, which is a new feature after JDK 1.5

Collection < E > extends Iterable < E >: all single column collections can use enhanced for
Public interface Iterable < T > implementation of this interface allows an object to be the target of a "foreach" statement.
Enhanced for loop: used to traverse collections and arrays
Format:
For (data type variable name of set / array: set name / array name){
Sout (variable name);

    }

 1 package demosummary.collection;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Iterator;
 6 
 7 public class IteratorTest {
 8     public static void main(String[] args) {
 9         //Create a collection
10         Collection<String> obj = new ArrayList<>();
11         //Add elements to the collection
12         obj.add("DMAR");
13         obj.add("Prince");
14         obj.add("Debon");
15         obj.add("Blademaster");
16         //Using polymorphism to create implementation class objects
17         Iterator<String> iter = obj.iterator();
18         //Enhance for
19         for (String str : obj) {
20             System.out.println(str);
21         }
22     }
23 }

Collection common tool class

java.utils.collections is a collection tool class used to operate on collections. Some methods are as follows:
Public static < T > Boolean addall (collection < T > C, T... elements): add some elements to the collection.
Public static vold shuffle (list <? > 1List): scramble order: scramble collection order.

 1 package demosummary.collection;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 import java.util.Collections;
 6 
 7 /*
 8       public static <T> boolean addAll(Collection<T> C,T... elements) :Add some elements to the collection.
 9     public static void shuffle(List<?> 1list) :Disorder order: disorder the order of assembly.
10     public static <T> void sort(List<T> list) :Sorts the elements in the collection according to the default rules.
11     public static <T> void sort(List<T> ist, Comparator<? super T> ) :Sorts the elements in the collection according to the specified rules.
12  */
13 public class CollectionTools {
14     public static void main(String[] args) {
15         ArrayList<String> obj = new ArrayList<>();
16         //How to add elements at the beginning
17 //        obj.add("DMAR");
18 //        obj.add("Prince");
19 //        obj.add("Debon");
20 //        obj.add("Blademaster");
21 
22         /*
23               public static <T> boolean addAll(Collection<T> C,T... elements) :Add some elements to the collection.
24          */
25 
26         //use collection To add elements
27         Collections.addAll(obj,"DMAR","Prince","Debon","Blademaster");
28         System.out.println(obj);//[DMAR, Prince, Debon, Blademaster]
29 
30         /*
31             public static void shuffle(List<?> 1list) :Disorder order: disorder the order of assembly.
32          */
33         Collections.shuffle(obj);
34         System.out.println(obj);//[Prince, DMAR, Debon, Blademaster]
35 
36     }
37 }

Public static < T > void sort (list < T > list): sorts the elements in the collection according to the default rules.
Public static < T > void sort (list < T > ist, comparator <? Super T >): sorts the elements in the collection according to the specified rules.

 1 package demosummary.collection;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.Comparator;
 6 
 7 public class CollectionTools02 {
 8     public static void main(String[] args) {
 9         //Create a collection object
10         ArrayList<Integer> obj = new ArrayList<>();
11         //Use collection Method add element
12         Collections.addAll(obj,4,3,2,1);
13         //  public static <T> void sort(List<T> list) :Sorts the elements in the collection according to the default rules.
14         //Default is ascending
15         Collections.sort(obj);
16         System.out.println(obj);//[1, 2, 3, 4]
17 
18         /*
19             public static <T> void sort(List<T> ist, Comparator<? super T> ) :Sorts the elements in the collection according to the specified rules.
20          */
21         //Create a collection object
22         ArrayList<Person> obj01 = new ArrayList<>();
23         //Add elements to collection
24         obj01.add(new Person("DMAR",18));
25         obj01.add(new Person("Prince",19));
26         obj01.add(new Person("Debon",20));
27         obj01.add(new Person("Blademaster",18));
28         //Output the sorting of the original set
29         System.out.println(obj01);
30         //Use collection Sort by specified rules
31         Collections.sort(obj01, new Comparator<Person>() {
32             @Override
33             public int compare(Person o1, Person o2) {
34                 //Sort by size
35                 int result = o1.getAge()-o2.getAge();
36                 if (result==0){
37                     result=o1.getName().charAt(0)-o2.getName().charAt(0);
38                 }
39                 return result;
40             }
41         });
42         System.out.println(obj01);
43     }
44 }

Posted by readourlines on Sat, 02 Nov 2019 23:03:01 -0700