当前位置:网站首页>Collection collection
Collection collection
2022-07-28 17:47:00 【night_ du】
aggregate
Concept
Object's container , Defines common methods for operating on multiple objects . The function of array can be realized
Different from array
- Array length is fixed , The set length is not fixed
- Arrays can store basic types and reference types , A collection can only store reference types
- Location :java.util.*;

Collection aggregate
Definition
Collection: The root interface of the architecture , Represents a group of objects , Become “ aggregate ”, Multiple ⼦ Pick up ⼝ And implementation classes , We call it Collection system
Collection hierarchy Root interface in .Collection Represents a set of objects , These objects are also called collection The elements of . some collection Duplicate elements are allowed , Others are not allowed to . some collection Is ordered , Others are disordered .
classification
- List Interface : Orderly 、 With subscript 、 Elements can be repeated
- Queue queue ,: In addition to priority , Maintain the principle of first in, first out
- Set Interface : disorder 、 No subscript 、 Elements cannot be repeated
Use
- add to :add(“ Elements ”);
- Delete :remove(“ Elements ”);
- Traverse :foreach Or iterators , Collection cannot delete elements when traversing , Unless the iterator deletes the element
for (Object object : collection) { - iterator :Iterator iterator = collection.iterator();
Iterator:hasNext()、next()、remove() - Judge :contains(“ Elements ”)、isEmpty()
public class Test1 {
public static void main(String[] args) {
// establish ArrayList
Collection collection = new ArrayList();
// add to
collection.add(" Apple ");
collection.add(" Banana ");
collection.add(" watermelon ");
/* // Look at the number of elements System.out.println(collection.size()); // Display set element values System.out.println(collection); // Delete collection.remove(" watermelon "); System.out.println(collection); // Empty collection.clear(); System.out.println(collection.size());*/
// Traverse
/* First option :foreach Traverse for (Object object : collection) { System.out.println(object); }*/
/* Second option : Using Iterators ( An iterator is a method specially used to traverse a set ) * Iterator There are three ways : * hasNext(): If there are still elements that can iterate , Then return to true. * next(): Returns the next element of the iteration . * remove(): Delete current element * */
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
String s = (String) iterator.next();
System.out.println(s);
// Collection cannot delete elements during iterator iteration , Unless the iterator deletes
//collection.remove(s); Report errors :java.util.ConcurrentModificationException
//iterator.remove(); // Iterators can delete
}
//System.out.println(collection.size());
/* for (int i = 0; i < collection.size(); i++) { System.out.println(iterator.next()); }*/
// Determine whether an element exists
System.out.println(collection.contains(" Banana "));
// Determines if the set is empty
System.out.println(collection.isEmpty());
}
}
Example
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Test2 {
public static void main(String[] args) {
// establish Collection aggregate
Collection collection = new ArrayList();
// establish Student object
Student student1 = new Student(21, "jack");
Student student2 = new Student(14, "mike");
Student student3 = new Student(19, "night");
// Additive elements
collection.add(student1);
collection.add(student2);
collection.add(student3);
//System.out.println(collection.size());
//System.out.println(collection.toString());
// Remove elements
//collection.remove(student1);
//System.out.println(collection.size());
//System.out.println(collection.toString());
// Empty elements
// Just delete in the collection , however student1 Still there, , Delete student1 Pointer in set
//collection.clear();
// Traversing elements
/* for (Object obj:collection) { Student student=(Student)obj; System.out.println(student); }*/
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Student str = (Student) iterator.next();
System.out.println(str);
}
}
}
class Student {
private int age;
private String name;
@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
public Student() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
belt All Of ⽅ Law
- boolean addAll(Collection c) Will specify collection All elements in are added to this collection in
- boolean removeAll(Collection c) To move in collection Those are also included in the designation collection All elements in
- boolean containsAll(Collection c) If so collection Include designation collection All elements in
- boolean retainAll(Collection c) Just keep this collection Those are also included in the designation collection The elements of
public static void main(String[] args) {
Collection<Student> collection = new ArrayList<>();
Student student1 = new Student("⼩ red ", 18);
Student student2 = new Student("⼩ bright ", 19);
collection.add(student1); // add to ⽅ Law
collection.add(student2);
Collection<Student> collection2 = new ArrayList<>();
Student student3 = new Student("⼩ Brightness ", 18);
collection2.add(student1);
collection2.add(student3);
// take collection2 The elements in the collection are added to collection Collection
collection.addAll(collection2);
System.out.println(collection.size());// result : 4
// Judge collection Does the collection contain collection2 All elements in the collection
boolean flg = collection.containsAll(collection2);
System.out.println(flg);// result : true
// Only in collection Keep the same elements in both sets
collection.retainAll(collection2);
System.out.println(collection.size());// result : 3
}
List Interface
List
Definition
List aggregate : Orderly 、 With subscript 、 Elements can be repeated
Set system
- ArrayList Array is used at the bottom ( Thread unsafe )
- LinkedList The bottom layer uses linked list
- Vector Array is used at the bottom ( Thread safety , It is not recommended to use )
iterator
Definition
iteration ( Traverse ) Elements stored in the collection
Traversal form
- Acquisition iterator
- mode hasNext() Method to determine whether the next element exists
- call next() Method to get the element
public static void main(String[] args) {
Collection<Student> collection = new ArrayList<>();
Student student1 = new Student("⼩ red ", 18);
Student student2 = new Student("⼩ bright ", 19);
Student student3 = new Student("⼩ Brightness ", 18);
collection.add(student1); // add to ⽅ Law
collection.add(student2);
collection.add(student3);
//for The form of the cycle
for(Iterator<Student> it = collection.iterator();it.hasNext();){
Student student = it.next();
System.out.println(student);
}
//while The form of the cycle
Iterator<Student> it = collection.iterator();
while(it.hasNext()){
Student student = it.next();
System.out.println(student);
}
}
Method
Create set :
List list = new ArrayList();Additive elements :
add to :list.add(“ millet ”);
Specify subscript location to add :list.add(0, “ Huawei ”);Delete 、 Empty
Delete... According to subscript , An error will be reported when the array is out of bounds , Otherwise, turn into Object type \ Packaging
Delete ( Element subscript ):list.remove(2);
Delete... According to subscript , An error will be reported when the array is out of bounds , Otherwise, turn into Object type \ Packaginglist.remove((Object)20); list.remove(new Integer(20)); Delete ( Element value )list.remove(“ Apple ”);
Empty :list.clear();
Traverse
for Loop traversal :
for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));}enhance for Traverse :
for (Object obj : list) {System.out.println(obj); }Iterator traversal :
Iterator iterator=list.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next());}List iterator traversal :
Positive traversal :ListIterator listIterator=list.listIterator(); while (listIterator.hasNext(){ System.out.println(listIterator.nextIndex(+":"+listIterator.next());}Reverse traversal :
while (listIterator.hasPrevious()){ System.out.println(listIterator.previousIndex()+":"+listIterator.previous());}
Judge
Element of judgement :list.contains(“ millet ”)
Determine whether it is null :list.isEmpty()Get the subscript position of the element value :list.indexOf(“ millet ”)
Return subsets ( Before closed after opening ):List subList=list.subList(1,2);
Example :
package util;
import java.util.*;
/** * List: Orderly 、 With subscript 、 Can be repeated */
public class Test3 {
public static void main(String[] args) {
// establish List aggregate
List list = new ArrayList();
// Additive elements
list.add(" millet ");
// Add an element at the specified subscript position
list.add(0, " Huawei ");
list.add(" Apple ");
//System.out.println(list.size());
//System.out.println(list.toString());
// Delete
//list.remove(2); // Element subscript
//list.remove(" Apple "); // Element value
//System.out.println(list.toString());
// Empty
//list.clear();
// Traverse
// Use for Loop traversal
/*for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); }*/
// Use enhancements for
/*for (Object obj : list) { System.out.println(obj); }*/
// Use iterators to traverse
/* Iterator iterator=list.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); }*/
// Use the list iterator to traverse str
// Can be positive 、 Reverse traversal 、 add to 、 modify 、 Remove elements
ListIterator listIterator=list.listIterator();
// Positive traversal
while (listIterator.hasNext()){
System.out.println(listIterator.nextIndex()
+":"+listIterator.next());
}
// Reverse traversal
while (listIterator.hasPrevious()){
System.out.println(listIterator.previousIndex()
+":"+listIterator.previous());
}
// Judge
System.out.println(list.contains(" millet "));
System.out.println(list.isEmpty());
// To obtain position
System.out.println(list.indexOf(" millet "));
}
}
List Implementation class
ArrayList
Array structure implementation , Quick query 、 Add or delete slowly
JDK1.2 After version , It's very efficient , Thread unsafe
1、 Create objects :ArrayList arrayList = new ArrayList();
2、 add to 、 Delete 、 Empty elements
add to :arrayList.add(30);
Delete :arrayList.remove(new Integer(20));
Empty :arrayList.clear();
3、 Traverse :fori、foreach、Iterator、ListIterator
Source code analysis
The default volume :DEFAULT_CAPACITY = 10; If you don't add elements , Capacity is 0
The default capacity for collection creation is 0, Add element expansion to 10, The second expansion is the previous 1.5 times
An array of elements :elementData
The actual number of elements :size
add() Add element code flow :
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
Vector
Array structure implementation , Quick query 、 Add or delete slowly
JDK1.0 edition , Slow operation efficiency , Thread safety
1、 Create objects :Vector vector = new Vector<>();
2、 add to 、 Delete 、 Empty elements
add to :vector.add(“ strawberry ”);
Delete :vector.remove(“ Banana ”);
Empty :vector.clear();
3、 Traverse :fori、foreach、Iterator、ListIterator、Enumeration
Enumeration enumeration=vector.elements();
while (enumeration.hasMoreElements()){
System.out.println(enumeration.nextElement());}
LinkedList
characteristic
Linked list structure implementation , Additions and deletions quickly , Slow query
Double linked list : Each node records the location of the previous node , Also record the location of the next node
And ArrayList Array difference
ArrayList -- Array structure , A continuous space
Add or delete slowly , Quick query
- The existing array is long enough , At the end of the increase -- There is no speed problem
- The existing array is not long enough , At the end of the increase -- You need to create a new array , Copy the data of the original array , Add new elements
- The existing length is sufficient , Add... In the middle -- Move each element after the specified position backward by one bit
- The existing array is not long enough , Add... In the middle -- Array capacity + Move the position of the array in the array
LinkedList -- Chain table structure
Additions and deletions quickly , It is slow to check and correct
- Add or delete : You only need to change the direction of the two nodes before and after to insert the element 、 Delete
- Check and modify : Only find the previous element , To find the next element . Must start from scratch
Use
Create objects :
LinkedList linkedList = new LinkedList();add to 、 Delete 、 Empty elements
add to
list.add("first"); list.add("second"); list.add(0, "zera");Delete
// Head removal System.out.println(list.remove()); System.out.println(list.poll()); System.out.println(list.peekFirst()); // Tail removal System.out.println(list.pollLast()); // Just look at , Do not remove System.out.println(list.peek()); System.out.println(list.peekFirst()); System.out.println(list.pollLast());Empty
list.clear();
Traverse :fori、foreach、Iterator、ListIterator
Source code
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
ArrayList、Vector、LinkedList Use demonstration of
package util;
import java.util.*;
public class Demo1 {
public static void main(String[] args) {
//ArrayListTest();
//VectorTest();
//LinkedListTest();
}
/** * ArrayList Use * Array storage structure , It's fast , Add or delete slowly */
public static void ArrayListTest() {
// Create objects
ArrayList arrayList = new ArrayList();
// Additive elements
arrayList.add(10);
arrayList.add(20);
arrayList.add(30);
arrayList.add(40);
//System.out.println(arrayList.size());
//System.out.println(arrayList.toString());
// Remove elements
//arrayList.remove(new Integer(20));
//System.out.println(arrayList.toString());
// Empty elements
//arrayList.clear();
// Traversing elements
/*for (int i = 0; i < arrayList.size(); i++) { System.out.println(arrayList.get(i)); }*/
/*for (Object obj:arrayList) { System.out.println(obj); }*/
/* Iterator iterator=arrayList.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); }*/
// Positive traversal
ListIterator listIterator = arrayList.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
// Reverse traversal
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
// Element of judgement
System.out.println(arrayList.contains(10));
System.out.println(arrayList.isEmpty());
// lookup
System.out.println(arrayList.indexOf(30));
}
/** * Vector Use * Array structure */
public static void VectorTest() {
// Create objects
Vector vector = new Vector<>();
// Additive elements
vector.add(" strawberry ");
vector.add(" Banana ");
vector.add(" watermelon ");
//System.out.println(vector.size());
//System.out.println(vector.toString());
// Remove elements
//vector.remove(" Banana ");
//vector.remove(1);
// Empty elements
//vector.clear();
// Traversing elements
/* for (int i = 0; i <vector.size() ; i++) { System.out.println(vector.get(i)); }*/
/*for (Object obj : vector) { System.out.println(obj); }*/
/* Iterator iterator=vector.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); }*/
/* ListIterator listIterator = vector.listIterator(); while (listIterator.hasNext()) { System.out.println(listIterator.next()); } while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); }*/
// Use the enumerator to traverse
Enumeration enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
// Judge
System.out.println(vector.contains(" watermelon "));
System.out.println(vector.isEmpty());
}
/** * LinkedList Use together * Two way link structure */
public static void LinkedListTest() {
// Create objects
LinkedList linkedList = new LinkedList<>();
// Additive elements
linkedList.add(" watermelon ");
linkedList.add(" strawberry ");
linkedList.add(" Apple ");
linkedList.add(0, " Hami melon ");
//System.out.println(linkedList.size()+" "+linkedList.toString());
// Remove elements
//linkedList.remove(" Apple ");
//System.out.println(linkedList.size()+" "+linkedList.toString());
// Empty elements
//linkedList.clear();
//System.out.println(linkedList.size()+" "+linkedList.toString());
// Traversing elements
/*for (int i = 0; i <linkedList.size() ; i++) { System.out.println(linkedList.get(i)); }*/
/*for (Object o : linkedList) { System.out.println(o); }*/
/* Iterator iterator=linkedList.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } ListIterator listIterator=linkedList.listIterator(); while (listIterator.hasNext()){ System.out.println(listIterator.next()); } while (listIterator.hasPrevious()){ System.out.println(listIterator.previous()); }*/
// Element of judgement
System.out.println(linkedList.contains(" pumpkin "));
System.out.println(linkedList.isEmpty());
}
}
ArrayList and LinkedList The difference between

Java Generics are JDK1.5 A new feature introduced in , Its essence is parametric type , Pass the type as an argument .
Common forms are generic classes 、 Generic interface 、 Generic methods .
grammar :
·<T...>T It's called a type placeholder , Represents a reference type .
benefits :
·(1) Improve code reuse
·(2) Prevent type conversion exceptions , Improve the security of the code
Generic
Generic classes
benefits
- carry ⾼ Security ( Will transport ⾏ The error of period is converted to compilation period )
- Save the trouble of forced rotation
- In its work ⽤ The domain can be unified ⼀ Parameter type
Use
grammar : Class name
T Represents a placeholder for the type , Represents a reference type , If you use multiple, separate them with commas MyGeneric<T,W,F>
- Use generics T Create variables :T t;
- Add method , Use generics T As a parameter of the method :public void show(T t) {}
- Use generics as the return value of the method :public T getT() {return t;}
Be careful
- Generics can only use reference types
- Different generic objects cannot be assigned to each other
origin
- Type through Object The problem of transformation leads to ⼊
- In the early Object Type can accept any object type , But in practice ⽤ in , There will be problems with type conversion . There is a hidden danger , therefore Java Generics are provided to solve this security problem .
public class Generic {
private Object object;
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
Example :
package util;
/** * Generic classes * grammar : Class name <T> * T Represents a placeholder for the type , Represents a reference type , If you use multiple, separate them with commas MyGeneric<T,W,F> * * @param <T> */
public class MyGeneric<T> {
//1、 Use generics T Create variables
T t;
//2、 Add method , Use generics T As a parameter of the method
public void show(T t) {
System.out.println(t);
}
//3、 Use generics as the return value of the method
public T getT() {
return t;
}
}
class TestMyGeneric {
public static void main(String[] args) {
MyGeneric<String> myGeneric = new MyGeneric<String>();
myGeneric.t = "hello";
System.out.println(myGeneric.t);
myGeneric.show(" Hello everyone ");
String str = myGeneric.getT();
MyGeneric<Integer> myGeneric1 = new MyGeneric<Integer>();
myGeneric1.t = 10;
System.out.println(myGeneric1.t);
myGeneric1.show(200);
Integer integer = myGeneric1.getT();
}
}
wildcard
Generic wildcard <?>, Also known as diamond wildcard
Any type , If it's not clear , Namely Object And whatever Java class
public static void main(String[] args) { ArrayList<String> arrayList1 = new ArrayList<>(); ArrayList<Integer> arrayList2 = new ArrayList<>(); List<?> list = arrayList1; list = arrayList2; }?extend E
Down limit E And E Subclasses of
?super E
Limit upward E And their parents
Generic interface
Format
grammar : The interface name <T>
Be careful : Cannot create generic static constants
Implementation class of interface
- When creating an implementation class, determine the type of the implementation class :class Test implements MyInterfece {}
- When creating an implementation class, you are not sure about the type of the implementation class , Determine the type when instantiating :class Test1 implements MyInterfece {}
/** * Generic interface * grammar : The interface name <T> * Cannot create generic static constants */
public interface MyInterfece<T> {
String name = " Zhang San ";
T servrt(T t);
}
/** * Implementation class of interface , When creating an implementation class, determine the type of the implementation class */
class Test implements MyInterfece<String> {
@Override
public String servrt(String s) {
System.out.println(s);
return s;
}
}
/** * Implementation class of interface , When creating an implementation class, you are not sure about the type of the implementation class , Determine the type when instantiating * * @param <T> */
class Test1<T> implements MyInterfece<T> {
@Override
public T servrt(T t) {
System.out.println(t);
return t;
}
}
class MyInterfeceTest {
public static void main(String[] args) {
Test test = new Test();
test.servrt("zdand");
Test1<Integer> test1 = new Test1<>();
test1.servrt(1000);
}
}
Generic methods
Format
grammar : return type
Use
public class MyGenericMethod {
public <T> void show(T t) {
System.out.println(" Generic methods " + t);
}
}
class MyGenericMethodTest {
public static void main(String[] args) {
//T The type of is determined by the incoming data
MyGenericMethod myGenericMethod = new MyGenericMethod();
myGenericMethod.show(1000);
myGenericMethod.show(" China ");
}
}
Generic set
Concept
Parameterized types 、 Type safe set , Mandatory collection elements must be of the same type .
characteristic
- Compile time to check , Instead of throwing an exception at runtime .
- During the interview , There is no need to type cast ( Unpacking ).
- References between different generics cannot be assigned to each other , There is no polymorphism in generics .
Use
package util;
import java.util.ArrayList;
import java.util.Iterator;
public class Demo {
public static void main(String[] args) {
/* ArrayList arrayList = new ArrayList(); // You can add data of various data types arrayList.add("123"); arrayList.add(100); // When traversing data , An error will be reported when converting all data from a certain data type :java.lang.ClassCastException for (Object object : arrayList) { String s = (String) object; System.out.println(s); }*/
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("1231");
// Unable to add String Data outside the type , Because it's creating arrayList The data type has been determined
//arrayList.add(1);
for (String s : arrayList) {
System.out.println(s);
}
Iterator<String> iterator = arrayList.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
System.out.println(str);
}
}
}
Generic summary
Java Generics are JDK1.5 A new feature introduced in , Its essence is parametric type , Pass the type as an argument .
Common forms are generic classes 、 Generic interface 、 Generic methods .
grammar :
·〈T,.>T It's called a type placeholder , Represents a reference type .
benefits :
·(1) Improve code reuse
·(2) Prevent type conversion exceptions , Improve the security of the code
Set aggregate
characteristic : disorder 、 No subscript 、 Element is not repeatable .
Method : All inherited from Collection The method in .
1、 Create set :Set set = new HashSet<>();
2、 Additive elements :
add to :set.add(“ millet ”);
3、 Delete 、 Empty
Delete :set.remove(“ millet ”);
Empty :set.clear();
4、 Traverse
enhance for Traverse :for (String s : set)
Iterator traversal :Iterator iterator = set.iterator();
5、 Judge
Element of judgement :set.contains(“ millet ”)
Determine whether it is null :set.isEmpty()
package util;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SetCollection {
public static void main(String[] args) {
// Create objects
Set<String> set = new HashSet<>();
// Additive elements
// You can add duplicate data when adding , But this data is not in the set
set.add(" Huawei ");
set.add(" millet ");
set.add(" millet ");
set.add(" millet ");
//System.out.println(set.size());
//System.out.println(set.toString());
// Remove elements
//set.remove(" millet ");
// Empty elements
//set.clear();
// Traversing elements
// enhance for
for (String s : set) {
System.out.println(s);
}
// Iterator traversal
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Judge
System.out.println(set.isEmpty());
System.out.println(set.contains(" millet "));
}
}
Set Implementation class
HashSet
be based on HashCode Calculation element storage location .
When the hash code stored in the element is the same , Would call equals Confirm , If the result is true, Then refuse the latter to deposit .
Create objects :HashSet<String> set = new HashSet<>();
( remarks : The other with set Agreement )
stored procedure
1、 according to hashcode Calculate where to save , If this location is empty , Save directly , If it is not empty, perform the second step
2、 perform equals(), If equals() by true, It's called repetition , Otherwise form a linked list
equals() and hashcode() rewrite
public class Person {
private int age;
private String name;
public Person() {
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/** * rewrite hashCode * * @return */
@Override
public int hashCode() {
int n1 = this.name.hashCode();
int n2 = this.age;
return n1 + n2;
}
/** * rewrite equals * * @param o * @return */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (o instanceof Person) {
Person person = (Person) o;
if (this.name.equals(person.getName()) && this.age == person.getAge()) {
return true;
}
}
return false;
}
}
TreeSet
Definition
Realized SortedSet Interface , Sort the size of the elements , Form a tree structure ( Red and black trees ), Elements cannot exist repeatedly
The stored element must implement Comparable Interface , And rewrite compareTo()
SortedSet() Source code
public interface SortedSet<E> extends Set<E> { Comparator<? super E> comparator(); } public interface Comparator<T> { int compare(T o1, T o2); }
Construction method
- TreeSet() structure ⼀ A new empty set, The set According to its element ⾃ Natural sequence ⾏ Sort
- TreeSet(Comparator <? super E> comparator) structure ⼀ An empty one TreeSet, He was appointed ⽐ Comparator advance ⾏ Sort
Common methods
add(E e) Add the specified element to this set
first() Back here set The current number ⼀ Elements
last() Back here set At the end of the current ⼀ Elements
floor() Back here set in ⼩ Equal to the most of a given element ⼤ Elements , Returns if it does not exist null
higher() Back here set It's very strict ⼤ At the most of a given element ⼩ Elements , Returns if it does not exist null
import java.util.SortedSet; import java.util.TreeSet; public class TreeSetDemo { public static void main(String[] args) { TreeSet<Integer> treeSet = new TreeSet<Integer>(); treeSet.add(1); treeSet.add(23); treeSet.add(423); treeSet.add(14); treeSet.add(67); for (Object o : treeSet) { System.out.print(o + "\t"); } // Get the largest element in the collection that is smaller than the given data , If there is no return null System.out.println(treeSet.floor(54)); // Get the smallest element in the set that is larger than the given data , If there is no return null System.out.println(treeSet.higher(54)); System.out.println(treeSet.first());// The first element System.out.println(treeSet.last());// The last element System.out.println(treeSet.size());// length System.out.println(treeSet.pollFirst());// Remove the first element System.out.println(treeSet.pollLast());// Remove the last element } }
Add principle
TreeSet Will the second ⼀ Add an element as the midpoint , Elements added later will follow the midpoint first ⾏⽐ a , If ⼤ Yu then followed ⽐ The element to the right of the element is followed by ⽐ a , If ⼩ Yu then followed ⽐ The element to the left of the element then ⽐ a , until ⽆ Can't find ⽐ More elements , The newly added element will be placed in the current position
matters needing attention
- TreeSet The storage principle of the set limits that the stored elements must be compared
- Elements either implement Comparable Interface , Or to achieve Comparator Interface , Otherwise, the program reports an error
Comparable
When TreeSet Set add reference type ( No int These foundations and String etc. , It's a class written by a person ) Data time , Will be submitted to the : Error of type conversion failure , as follows :
public class Person {
private int age;
private String name;
public Person() {
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
public class SetCollection {
public static void main(String[] args) {
// Create objects
TreeSet<Person> set = new TreeSet<>();
Person person1 = new Person(11, "jack");
Person person2 = new Person(12, "son");
Person person3 = new Person(20, "mkisq");
set.add(person1);
set.add(person2);
set.add(person3);
System.out.println(set.toString());
}
}
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-4ie3C2r9-1645535987110)(F:\ Note file \JavaSE\12、 aggregate \ aggregate .assets\image-20210924101423240.png)]](/img/0f/0d2e8c415f1616e4e3c4d66122a722.png)
Why? :
because TreeSet The storage structure of is red black tree , Data needs to be compared , and Person Data cannot be compared , The data is all on one side , Out of balance .
When comparing elements in a set , Then the set has no comparator , The element will turn into Comparator Type and call comparaTo(), So we have to rewrite
compareTo
- Return value less than 0, Indicates that the current element is smaller than the compared element
- The return value is equal to 0, Indicates that the current element is equal to the element being compared
- Return value greater than 0, Indicates that the current element is larger than the compared element
processing method :
Person Realization Comparable Interface , And rewrite compareTo Method : Compare data sizes
public class Person implements Comparable<Person> {
/** * rewrite compareTo Method * Compare data sizes : First compare with name, Later ratio age * * @param o * @return */
@Override
public int compareTo(Person o) {
int n1 = this.getName().compareTo(o.getName());
int n2 = this.age - o.getAge();
return n1 == 0 ? n2 : n1;
}
}
Comparator
comparator It's an interface , Need to rewrite compare()
public static void main(String[] args) {
// Create objects
TreeSet<Person> set = new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int n1 = o1.getAge() - o2.getAge();
int n2 = o1.getName().compareTo(o2.getName());
return n2 == 0 ? n1 : n2;
}
});
}
Collections
Map aggregate
Map Interface features
- Used to store arbitrary key value pairs (key-value)
- key : disorder 、 No subscript 、 No repetition ( only )
- value : disorder 、 No subscript 、 Allow repetition
Map Common methods of parent interface
V put(K key,,V value): Put objects into a collection , Associated key value .key If it is repeated, the original value will be covered .
Object get(Object key): Get the corresponding value according to the key .
Set: Back to all key.
Collectionvalues(): Returns... Containing all values Collection aggregate .
Set<Map.Entry<K,V>> : Key value matching Set aggregate .
public class MapDemo { public static void main(String[] args) { // establish Map<Integer, String> map = new HashMap<>(); // Additive elements K V map.put(1, null); map.put(null, "pear"); map.put(3, "new oranage"); map.put(3, "oranage");// Replace... In a certain position value value System.out.println(map.get(122));// No error is reported here because the data is not processed System.out.println(reData(map.get(122)));// Data processing , Prompt null pointer error // Whether the key is associated with the value , If there is no return null( Only care about key If there is a value , If there is no return null) System.out.println(map.putIfAbsent(1, "111")); // Determine whether the key value exists System.out.println("111".equals(map.getOrDefault(5, "111")) ? " nothing " : "111"); System.out.println(map.get(3));// Get a key Upper value, There is no return null System.out.println(map.isEmpty());// Judge map Is it empty System.out.println(map.containsKey(2));// Judge map Is there a specified key System.out.println(map.containsValue("xi"));// Judge map Is there a specified value System.out.println(map.entrySet());// View all data System.out.println(map.keySet());// View all key map.putAll(map);// add to map aggregate System.out.println(map.remove(3));// Remove execution key And corresponding value System.out.println(map.size());// Return length System.out.println(map.values());// View all value map.clear(); // Empty elements HashMap<Integer,String> hashMap=(HashMap<Integer, String>) ((HashMap<Integer, String>) map).clone();// Back here HashMap Shallow copy of instance : Keys and values themselves are not cloned } public static String reData(String s) { return s.toUpperCase().substring(0); } }
forEach、 enhance for
Definition
- Iterator Short form of
- Simplify arrays and Collection Traversal of the set
Format
for( Element data type Variable : An array or Collection aggregate ){
You can use variables , Variables are elements
}
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>(new MyComparator());
Student student1 = new Student("⼩ red ");
Student student2 = new Student("⼩ bright ");
Student student3 = new Student("⼩ Li ");
set.add(student1);
set.add(student2);
set.add(student3);
for (Student student : set) {
System.out.println(student);
}
}
Deletion of iteration
- Ordinary for loop , You can delete , But you need corner marks
- iterator , You can delete , But you have to use the iterator's own remove(), Otherwise, exceptions will be modified concurrently
ap.containsKey(2));// Judge map Is there a specified key
System.out.println(map.containsValue(“xi”));// Judge map Is there a specified value
System.out.println(map.entrySet());// View all data
System.out.println(map.keySet());// View all key
map.putAll(map);// add to map aggregate
System.out.println(map.remove(3));// Remove execution key And corresponding value
System.out.println(map.size());// Return length
System.out.println(map.values());// View all value
map.clear(); // Empty elementsHashMap<Integer,String> hashMap=(HashMap<Integer, String>) ((HashMap<Integer, String>) map).clone();// Back here HashMap Shallow copy of instance : Keys and values themselves are not cloned } public static String reData(String s) { return s.toUpperCase().substring(0); } }
forEach、 enhance for
Definition
- Iterator Short form of
- Simplify arrays and Collection Traversal of the set
Format
for( Element data type Variable : An array or Collection aggregate ){
You can use variables , Variables are elements
}
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>(new MyComparator());
Student student1 = new Student("⼩ red ");
Student student2 = new Student("⼩ bright ");
Student student3 = new Student("⼩ Li ");
set.add(student1);
set.add(student2);
set.add(student3);
for (Student student : set) {
System.out.println(student);
}
}
Deletion of iteration
- Ordinary for loop , You can delete , But you need corner marks
- iterator , You can delete , But you have to use the iterator's own remove(), Otherwise, exceptions will be modified concurrently
- Super for The loop cannot delete
边栏推荐
- 点云处理---kd-tree
- Branch and loop (for and do while)
- Jerry ac692x --- matrix keyboard addition
- Database performance analysis and optimization (internal training materials of Aite future team)
- 域名解析问题记录
- C#中virtual(虚方法)的理解以及和abstract(抽象方法)的区别
- 【p5.js】实战临摹——国际象棋盘
- Map R language
- 【p5.js学习笔记】鼠标交互事件
- Convert the image file of input type='file'to Base64
猜你喜欢

.net MVC understanding

编译原理学习笔记1(编译原理概述与词法分析)

MySQL高级-MVCC(超详细整理)

都说软件测试是IT行业最差的,是这样的吗?

【C语言笔记分享】——动态内存管理malloc、free、calloc、realloc、柔性数组

小白必看的软件测试发展路线

PCA reports error in eigen (crossprod (t (x), t (x)), symmetric = true): 'x' has infinite value or missing value

软件测试真有网上说的那么好吗?

Students' 20 R language exercises

【p5.js】实战练习——无规则对称
随机推荐
软件测试培训需要多久?
【p5.js学习笔记】鼠标交互事件
【C语言笔记分享】自定义类型:结构体,枚举,联合(建议收藏)
@Detailed explanation of requestmapping
怎样将IDEA与码云进行绑定
软件测试真有网上说的那么好吗?
Collection集合
2021 National Undergraduate data statistics and Analysis Competition
MySQL高级-MVCC(超详细整理)
软件测试的培训机构靠谱吗
Solve package is not available (for R ve [package 'xxx' is not available (for R version x.y.z) "warning?]
Database performance analysis and optimization (internal training materials of Aite future team)
【Unity FPS】教程 | 使用Unity制作第一人称角色控制器
[阅读笔记] For Paper:R-CNN系列的三篇论文总结
Complete MySQL interview questions (updated in succession)
转行学习软件测试有前途吗?
es6 Promise
禅道项目管理软件,敏捷开发团队不可或缺的工具
零基础软件测试培训可靠吗?
Technical aspects passed easily, HR: those with only three years of experience in large factories are not worth 20K