Collection framework
Collection, like array, can save a group of elements, and provides related methods to operate elements, which is more convenient to use
Collections are used to store objects with different numbers (only objects can be saved). Collection classes are also called container classes;
Sets can be roughly divided into four systems: Set, List, Queue and Map;
1.Set represents an unordered and unrepeatable set;
2. java.util.List, a linear table, represents an ordered and repeatable set;
3.Queue, which is used to simulate the data structure of queue;
4.Map, which represents the set with mapping relationship;
Here, repeatability refers to whether the elements in the set can be repeated, and the criterion for determining repeated elements depends on the results of the element's own equals comparison. If it is true, it is considered to be a repeated element
Collection classes are located under the java.util package. These classes are derived from the collection and Map interfaces!
java.util.Collection interface:
java.util.Collection is the top-level interface of all collections. There are many implementation classes under Collection, so we have more data structures to choose from
Collection interface is the parent interface of Set, Queue and List interfaces.
The Collection interface defines the common methods of the three Collection systems.
Common methods of Collection interface:
Add elements, delete elements, return the number of elements, traverse the collection elements, and judge whether an element is included.
Map interface
Related methods in java collection framework
Collection creation, addition and output
// Collection c = new ArrayList(); Collection c = new HashSet(); c.add(new Point(1,2)); c.add(new Point(3,4)); c.add(new Point(5,6)); c.add(new Point(7,8)); c.add(new Point(1,2)); /* The collection overrides the toString method of Object. The output format is: [Element 1.toString(), element 2.toString(),...] */ System.out.println(c);
Determines whether the current collection contains the given element
boolean contains(Object o)
Judge whether the current set contains a given element. The judgment here is based on whether the given element is related to the set
The existing element has an equals comparison of true.
Point p = new Point(1,2); boolean contains = c.contains(p); System.out.println("contain:"+contains);
Deletes the given element from the collection
remove is used to delete a given element from the collection. It is also an element that is true compared with equals in the collection.
Note that collections that can hold duplicate elements are deleted only once.
c.remove(p); System.out.println(c);
Increase, clear, return length, judge empty set
Collection c = new ArrayList(); // boolean add(E e) // Adds an element to the current collection. Returns true when the element is successfully added c.add("one"); c.add("two"); System.out.println(c); // int size() // Returns the number of elements in the current collection int size = c.size(); System.out.println("size:"+size); // boolean isEmpty() // Judge whether the current set is empty (without any elements) boolean isEmpty = c.isEmpty(); System.out.println("Is it an empty set:"+isEmpty); // Empty collection c.clear(); System.out.println(c);
A collection holds references to elements
The collection can only store elements of reference type, and it stores the reference (address) of the element
Collection c = new ArrayList(); Point p = new Point(1,2); c.add(p); System.out.println("p:"+p);//p:(1,2) System.out.println("c:"+c);//c:[(1,2)] p.setX(2); System.out.println("p:"+p);//p:(2,2) System.out.println("c:"+c);//c:[(2,2)]
Operations between collections
Sets provide operations such as taking and merging sets, deleting intersection sets, judging inclusion subsets, etc
Adds all elements in the given collection to the current collection.
boolean addAll(Collection c) adds all elements in a given collection to the current collection. Returns true if the current collection has changed
Collection c1 = new HashSet();//Non repeatable element c1.add("java"); c1.add("c"); c1.add("c++"); System.out.println("c1:"+c1); Collection c2 = new ArrayList(); c2.add("android"); c2.add("ios"); c2.add("java"); System.out.println("c2:"+c2); /* boolean addAll(Collection c) Adds all elements in the given collection to the current collection. Returns true if the current collection has changed */ boolean tf = c1.addAll(c2); System.out.println(tf); System.out.println("c1:"+c1); System.out.println("c2:"+c2);
Determines whether the current collection contains all elements in a given collection
/* boolean containsAll(Collection c) Determines whether the current collection contains all elements in a given collection */ boolean contains = c1.containsAll(c3); System.out.println("Include all elements:"+contains);
Deletes the common elements in the current collection and the given collection
/* boolean removeAll(Collection c) Deletes the common elements in the current collection and the given collection */ c1.removeAll(c3); System.out.println("c1:"+c1); System.out.println("c3:"+c3);
Traversal Iterator of collection
Collection provides a unified way to traverse Collections: iterator mode
Iterator (iterator) is an interface for traversing elements in a Collection.
The iterator() method in the Collection interface returns an instance of the Iterator interface.
The steps followed by the iterator to traverse the collection are: ask, take and delete. Deleting elements is not necessary
Different collections implement an Iterator implementation class for traversing their own elements. We don't need to remember their names. We can regard them as iterators from a polymorphic point of view
◼ Iterator mainly provides the following methods:
- boolean hasNext() If the collection has not been iterated, return true;
- Object next() Returns the next element in the collection;
- void remove() Delete the last element returned by the next method in the collection.
//Get iterator Iterator it = c.iterator(); /* Related methods provided by iterators: boolean hasNext() Determine whether there are elements in the collection that can be traversed E next() Get the next element of the collection (the first element is obtained at the first call, and so on) */ while(it.hasNext()){ String str = (String)it.next(); System.out.println(str); } System.out.println(c);
During iterator traversal, elements cannot be added or deleted through the method of the collection
The Collection interface does not define an operation to get an element separately because it is not common. However, Collection provides the operation of traversing Collection elements. This operation is a general operation. No matter what type of Collection, this traversal mode is supported: iterator mode.
* Iterator iterator()
This method gets an iterator that traverses the elements of the current collection
The java.util.Iterator interface is an Iterator interface, which specifies the relevant operations of iterators traversing collections. Different collections provide an Iterator implementation class for traversing their own elements, but we don't need to know their names. We can use them as iterators in a polymorphic way.
The iterator traverses the collection in the following steps: ask - > get - > delete
Deletion is not required.
while(it.hasNext()){ String str = (String)it.next(); System.out.println(str); if("#".equals(str)){ /*The iterator requires that no elements be added or deleted through the collection method during traversal Otherwise, an exception will be thrown: ConcurrentModificationException*/ //c.remove(str); //The remove method of the iterator can delete the elements obtained through the next method from the collection. it.remove(); } }
List set
java.util.List interface, inherited from Collection
The List set is repeatable and ordered. It provides a way to access the set according to the index:
- Insert the element at the specified index in the collection;
- Deletes the element at the specified index from the collection;
- Returns the element at the specified index from the collection;
- Returns the index value of an element in the collection;
- From a collection, returns a subset of elements between the start index and the end index.
Common implementation classes: - java.util.ArrayList:Internal use array implementation,Better query performance. - java.util.LinkedList:Internal use of linked list implementation,The performance of adding and deleting elements at the beginning and end is better.
List collection common methods
List names = new ArrayList(); names.add("Lily"); names.add("Mary"); names.add("John"); names.add("Tony"); names.add("Lisa"); names.add("Mary"); System.out.println(names); //[Lily, Mary, John, Tony, Lisa, Mary]
get() and set()
Get element and action element
Overloaded add() and remove()
/* void add(int index,E e) Inserts the given element into the specified location */ names.add(1,"Lucy"); System.out.println(names); //[Lily, Lucy, Mary, John, Tony, Lisa, Mary] /* E remove(int index) Deletes and returns the element at the specified location */ //[one,six,three,four,five] String e = names.remove(1); System.out.println(names); //[Lily, Mary, John, Tony, Lisa, Mary] System.out.println("Deleted element:"+e); //Deleted element: Lucy
subList() method
List subList(int start,int end) gets the subset within the specified range in the current collection.
The two parameters are the start and end subscripts (including the head but not the tail)
Note: operations on subset elements are operations on the corresponding elements of the original set
System.out.println(names.subList(1,4)); //[Mary, John, Tony] // Get element subscript get the last subscript of the element System.out.println(names.indexOf("Mary") + "," + names.lastIndexOf("Mary")); //1,5
Sorting of sets
java.util.Collections class
Collections is a collection tool class, which defines many static methods for manipulating collections
Collections. Sort (List) method The List collection can be sorted naturally (from small to large)
//sort names.sort(new Comparator() { @Override public int compare(Object o1, Object o2) { String s1 = (String) o1; String s2 = (String) o2; if (s1 == null && s2 == null){ return 0; }else if (s1 ==null){ return -1; }else if (s2 ==null){ return 1; }else { return s1.compareTo(s2); } } }); System.out.println(names); // [John, Lily, Lisa, Mary, Mary, Tony]
ListIterator
List provides a listreader () method to return a listrator object;
The listlter interface inherits from the Iterator interface, which adds the following methods;
1.boolean hasPrevious() determines whether the element pointed to by the iterator has a previous element;
2.Object previous() Returns the previous element of the element pointed to by the iterator;
2.void add(Object o) Inserts an element at the position of the element pointed to by the iterator
for (int i = 0;i<names.size();i++){ System.out.print(i + ":" + names.get(i) + "\t"); } // 0:Lily 1:Mary 2:John 3:Tony 4:Lisa 5:Mary ListIterator iterator = names.listIterator(); while (iterator.hasNext()){ System.out.print(iterator.next() + " ") ; } System.out.println(); //Lily Mary John Tony Lisa Mary while (iterator.hasPrevious()){ System.out.print(iterator.previous() + " "); } System.out.println(); //Mary Lisa Tony John Mary Lily
ArrayList
ArrayList is a List interface based on array implementation;
ArrayList internally encapsulates an Object [] array with variable length;
By default, the initial length of the array is 10. You can also specify its initial length through the constructor parameter display;
Whenever the number of elements added exceeds the length of the array, ArrayList will automatically expand the length.
Vector
Vector and Stack are ancient collection classes with poor performance. They are not recommended!
1. Collections tool class can turn ArrayList into a thread safe class;
2. When the stack data structure needs to be used in the program, ArrayDeque is recommended.
1. Vector is also an array based implementation, which is the same as ArrayList;
2. Vector is thread safe, while ArrayList is non thread safe;
3. Vector has the overhead of ensuring thread safety, so its performance is not as good as ArrayList;
4. The subclass Stack of vector is used to simulate the data structure (LIFO) of Stack.
Arrays.ArrayList
List Arrays.asList(Object... o)
1. This method can convert multiple objects or an object array into a List set;
2. The actual returned type is the internal class of Arrays, also called ArrayList;
3. Arrays.ArrayList is a set of fixed length, which can be traversed, but cannot be added or deleted!
Set set
The Set collection is unordered and the of the same element is not allowed.
- The Set collection usually does not remember the order in which elements are added.
- The Set collection is not allowed to contain the same elements. Adding the same elements to the Set will fail (the method returns false).
- The common implementation classes of the Set interface include HaseSet, TreeSet and LinkedHashSet.
HaseSet,TreeSet,LinkedHashSet
- HashSet cannot guarantee the arrangement order of elements;
- LinkedHashSet adopts linked list structure to maintain the order of elements;
- TreeSet supports two sorting methods to ensure the order of elements.
1. The performance of HashSet is always better than TreeSet, because TreeSet needs to maintain the order of elements through red black tree algorithm;
2. For insert and delete operations, LinkedHashSet is slightly slower than HashSet, which is due to the increased cost of maintaining the linked list. However, because of the linked list, LinkedHashSet is faster during traversal!
HashSet
HashSet is a typical implementation of Set interface. It has the following characteristics:
- HashSet cannot guarantee the arrangement order of elements;
- The value of HashSet collection element can be null;
- HashSet is non thread safe. In multi-threaded environment, code must be used to ensure its synchronization.
HashSet
HashSet students = new HashSet(); students.add("first"); students.add("the second"); boolean a = students.add("the second"); //If false is returned, no error will be reported, but it will not be saved students.add("Third"); students.add(null); System.out.println(a); //false System.out.println(students); //[null, second, third, first]
LinkedHashSet
LinkedHashSet is a subclass of HashSet. It has all the characteristics of HashSet. At the same time, LinkedHashSet adopts linked list structure to maintain the insertion order of elements! dHashSet maintains the insertion of elements in a linked list structure
LinkedHashSet teachers = new LinkedHashSet(); teachers.add("three countries"); teachers.add("Water Margin"); teachers.add("Journey to the West"); teachers.add("The Dream of Red Mansion"); a = teachers.add("three countries"); teachers.add(null); System.out.println(a); //false System.out.println(teachers); //[Three Kingdoms, water margin, journey to the west, dream of Red Mansions, null]
TreeSet
TreeSet can ensure the arrangement order of elements. It has more methods than HashSet:
- Returns the first (last) element in the set;
- Returns the element before (after) the specified element in the collection;
- Returns a subset of a limited range of elements in a collection;
TreeSet scores = new TreeSet(); scores.add(83); scores.add(72); scores.add(95); scores.add(61); scores.add(29); scores.add(99); System.out.println(scores); //[29, 61, 72, 83, 95, 99] System.out.println(scores.first() + "-" + scores.last()); //29-99 // Returns elements smaller than 60. Returns elements larger than 60 System.out.println(scores.lower(60) + "-" + scores.higher(60)); //29-61 //Find an element smaller than this element System.out.println(scores.headSet(61)); //[29] //Find an element greater than or equal to this element System.out.println(scores.tailSet(61)); //[61, 72, 83, 95, 99]
TreeSet uses the data structure of red black tree to store elements. It supports two sorting methods: natural sorting and custom sorting.
Natural sorting
- When adding, call the compare To method of elements to compare the size of elements and arrange elements in ascending order;
- Objects added to TReeSet must implement Comparable. This interface defines the compareTo method;
- Many types provided by Java have implemented the Comparable interface, such as wrapper class, String, Date, etc
obj1.compareTo(obj2)
This method returns an integer of type int, and the return of 0 means that the objects are equal,
Returning a positive number means obj1 is larger, and returning a negative number means obj2 is larger.
//Natural sorting TreeSet names = new TreeSet(); names.add("Lily"); names.add("John"); names.add("Tony"); names.add("Lisa"); names.add("Mary"); System.out.println(names); //If the Comparable interface is not implemented, an error will be reported // TreeSet objs = new TreeSet(); // objs.add(new Object()); // objs.add(new Object()); // objs.add(new Object()); //If the type is different, an error will be reported if there is no comparability // TreeSet objs = new TreeSet(); // objs.add("dawdaw"); // objs.add(100);
Custom sorting
When creating sorting, pass in the instance of Comparator interface;
The Comparator interface defines the compare method, which is used to compare the sizes of two objects;
Instead of calling compare To(), TreeSet calls compare() to compare sizes.
obj1.compare(obj2)
This method returns an integer of type int, and the return of 0 means that the objects are equal,
Returning a positive number means obj1 is larger, and returning a negative number means obj2 is larger.
//Custom sorting TreeSet nums = new TreeSet(new Comparator() { @Override public int compare(Object o1, Object o2) { Number n1 = (Number) o1; Number n2 = (Number) o2; if (n1 == null && n2 == null){ return 0; }else if (n1 ==null){ return -1; }else if (n2==null){ return 1; }else if (n1.doubleValue() > n2.doubleValue()){ return 1; }else if (n1.doubleValue() < n2.doubleValue()){ return -1; }else { return 0; } } }); nums.add(null); nums.add(83.5); nums.add(37); nums.add(92.5); nums.add(54); nums.add(75); nums.add(60); System.out.println(nums);
If you want to sort in reverse, you can exchange the return value.
Conversion of sets and arrays
Convert collection to array
Collection provides a method: * * toArray * *, which can convert the current collection into an array
/* The overloaded toArray method requires an array to be passed in, and all elements of the collection will be stored in the array Return it after (provided that the array len gt h > = the size of the collection). If the given array is not long enough, The method will create an array with the same length as the collection size according to the given array type, and Return after storing the collection elements. */ String[] array = list.toArray(new String[list.size()]); System.out.println(array.length); System.out.println(Arrays.toString(array));
Variable length parameter
JDK5 Another feature introduced when:Variable length parameter Only one variable length parameter can be declared in a method,And must be the last parameter
dosome(1,"a"); dosome(1,"a","b"); dosome(1,"a","b","a","b","a","b","a","b","a","b"); dosome(1,new String[]{"1","2","3"}); } public static void dosome(int i,String... s){ /* Variable length parameter is actually an array in the method. Several parameters are passed in to the variable length parameter The array length is consistent with the number of arguments */ System.out.println(s.length); System.out.println("s:"+ Arrays.toString(s)); }
Convert array to List collection
Array tool class Arrays provides a static method * * asList() * *, which can convert an array into a List collection
/* If you want to add or delete a collection, you need to create a collection and then import the collection elements. All collections support a construction method with a parameter of Collection, which is used to create the current Collection and package it at the same time Contains all elements in a given collection */ List<String> list2 = new ArrayList<>(list); System.out.println("list2:"+list2); list2.add("seven"); System.out.println("list2:"+list2);
Note: the element operation on the array converted set is the operation corresponding to the original array
Because the array is of fixed length, the operation of adding or deleting elements to the collection is not supported, and an exception will be thrown: java.lang.unsupported operationexception