Common class
String class and StringBuffer class
The String class cannot change the contents of the String object. A new String is generated after each operation
The StringBuffer class can dynamically change the string and add, delete, modify and query the original object
The difference between equals() and "= ="
equals() only determines whether the values are equal
The "= =" judgment value also determines whether the references are equal
length (): gets the number of characters of the string
Length: gets the length of the array
toCharArray(): converts a string object to a character array
Three collections of Java
They are all interfaces and need to be implemented
- The collection class exists in the java.util package and is a container for storing objects
- Collection can only hold objects. If you store int data, it will be automatically converted into an object of Integer class. (each basic type in Java has a corresponding reference type)
- The collection stores references to multiple objects, and the object itself is still stored in heap memory.
- Collection can store different types and unlimited number of data types.
1.Set: out of order and cannot be repeated
HashSet
Store collection elements according to Hash algorithm -- easy access and search
Features: the arrangement order of elements is not guaranteed. It is not repeatable. It is not thread safe. Collection elements can store null
Stored procedure: when an element is stored in the HashSet set, the HashSet will call the hashCode() method of the object to obtain the hashCode value of the object, so as to determine the position of the object in the HashSet
notes: if the equals () of two elements returns true, but their hashCode () values are inconsistent, the hashSet will store them in different locations. (this point does not conflict with non repetition and should be understood carefully)
The HashSet class implements the Set interface, which inherits from the Collection interface
package setStudy1117; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class test01 { public static void main(String[] args) { Set set = new HashSet(); //Add element add set.add(1); set.add("a"); System.out.println(set); //Delete element set.remove(1); System.out.println(set); //Determine whether to include elements - contains System.out.println(set.contains(1)); //clear all elements set.clear(); System.out.println(set); //Traversal set———————— set.add("a"); set.add("b"); set.add("c"); set.add("d"); System.out.println(set); // 1. Use iterator Iterator iter = set.iterator(); //New iterator object while(iter.hasNext()){ //If there is the next one in the iterator System.out.println(iter.next()); } System.out.println("============================="); // 2. Iterate with enhanced for for (Object obj : set) { System.out.println(obj); } //Gets the number of elements in the collection System.out.println(set.size()); //How to show the non repeatability of a Set? At present, there are four abcd elements in the Set set.add("a"); System.out.println(set);//An a will not be added to the set, and the number of elements is still 4 //null can be stored in the collection, and to calculate an element, the size must be + 1 set.add(null); System.out.println(set); System.out.println(set.size()); } }
Iterator interface
It is mainly used to traverse the elements in the Collection. The iterator object is also called an iterator. The iterator is an interface and cannot create an object itself. If an iterator object is required, there must be an iterated Collection object, such as Iterator iter=set.iterator();
Necessary conditions for HashSet set to judge the equality of two objects:
- Both objects return true through equals()
- The hashCode() return values of the two objects are equal
generic paradigm
Used to limit that a collection can hold only one type of element
Format: HashSet < specify type > setstring = new HashSet < specify type > ();
public class test01 { public static void main(String[] args) { //A collection can store any type of data. Without specifying a generic type, it is equivalent to the default generic type of Object Set set = new HashSet(); set.add("a"); set.add(1); set.add(true); set.add("csdn"); System.out.println(set); //Specifies that the generic type is String HashSet<String> setString = new HashSet<>(); setString.add("ssdasdasd"); // setString.add(123);———————— The compilation will report an error and the type does not match }
TreeSet
TreeSet class is the implementation class of SortedSet interface. TreeSet can ensure that the collection elements are in sorting state
Two sorting methods:
- Natural sort (default), ascending
- Custom sorting
The use of TreeSet must be guaranteed to put objects of the same type, otherwise type conversion exceptions may occur (restricted by generics)
import java.util.Set; import java.util.TreeSet; public class test02 { public static void main(String[] args) { Set<Integer> set= new TreeSet<Integer>(); set.add(5); set.add(2); set.add(15); set.add(8); set.add(99); //Default natural sort, ascending System.out.println(set); //Output [2, 5, 8, 15, 99] //Use iterators to specify type traversal Iterator<Integer> iterator = set.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } }
How to put custom classes into TreeSet and sort them according to the specified attributes?
- Custom classes need to implement the interface Comparator (java.util). When implementing this interface, we must implement the abstract method compare in it
package setStudy1117; import java.util.Comparator; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class test02 { public static void main(String[] args) { Person person = new Person("Zhang San",25); Person person1 = new Person("Li Si",15); Person person2 = new Person("Wang Wu",55); Person person3 = new Person("lucy",35); Person person4 = new Person("caty",11); Set<Person> set= new TreeSet<Person>(new Person()); set.add(person); set.add(person1); set.add(person2); set.add(person3); set.add(person4); for (Person p : set) { System.out.println(p.name+": "+p.age); } } } class Person implements Comparator<Person> { //Save the Person object into the TreeSet type and sort it by age int age; String name; public Person() { } public Person(String name,int age) { this.name=name; this.age = age; } @Override public int compare(Person o1, Person o2) { //Positive order of age if (o1.age>o2.age){ return 1; }else if (o1.age<o2.age){ return -1; }else return 0; } }
Operation results
caty: 11
Li Si: 15
Zhang San: 25
lucy: 35
Wang Wu: 55
[learn about comparator.compare (), supplement]
2. List: ordered and repeatable
ArrayList class (thread unsafe)
(the Vector class is basically similar to ArrayList -- thread safe -- but it has been eliminated and will not be expanded here.)
-
The ArrayList class implements the List interface, which inherits from the Collection interface
-
Each element in the List collection has its corresponding order index. By default, the element index is set according to the order in which the elements are added
-
Some methods have been added to the List collection to manipulate the collection elements according to the index
package setStudy1117; import java.util.ArrayList; import java.util.List; public class test03 { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("b"); list.add("sadab"); list.add("asdasdasdb"); list.add("ssb"); System.out.println(list); //Output [b, sadab, asdasdb, SSB] //Accesses the element at the specified location by index System.out.println(list.get(2)); //Repeatability list.add("b"); list.add("sadab"); System.out.println(list); //Inserts an element at the specified location list.add(1,"f"); System.out.println(list); //Inserts a collection at the specified location List<String> list1 = new ArrayList<>(); //New collection list1 list1.add("123"); list1.add("456"); // list.addAll(2,list1); System.out.println(list); //Gets the index subscript of the first occurrence of the specified element in the collection. If not found, return - 1 System.out.println(list.indexOf("aaa")); System.out.println(list.indexOf("123")); System.out.println(list.indexOf("b")); //Gets the index subscript of the last occurrence of the specified element in the collection. If not found, return - 1 System.out.println(list.lastIndexOf("b")); //Removes the element at the specified location list.remove(7); System.out.println(list); //Changes the value of the element at the specified location list.set(0,"bbbbb"); System.out.println(list); //Intercept the subsequent elements at the specified location to form a new list List<String> list2 = list.subList(3,5);//Excluding the right boundary, the length of the new list is equal to the end minus the start System.out.println(list2); //Get collection length System.out.println(list.size()); } }
3. Map interface: has mapping relationship
- key and value can be data of any reference type (so there should be two generic types when creating a new object)
- The key in the Map cannot be repeated. The unique value can be found through the specified key
- The HashMap class is used to implement the Map interface
- HashMap does not guarantee element order
HashMap class (thread unsafe)
(HashTable class is basically similar to HashMap -- thread safe -- but it has been eliminated and will not be expanded here.)
package setStudy1117; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Test04 { public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); // The method of adding HashMap is put () map.put("Xiao Ming",1); map.put("Xiao Hong",551); map.put("White horse",51); map.put("Sustain",1); map.put("Buckle",1); System.out.println(map); //The output of the map is curly braces {}, with an equal sign connecting key value pairs //Value according to key System.out.println(map.get("Xiao Hong")); //Delete element according to key map.remove("Xiao Hong"); System.out.println(map); //Get length System.out.println(map.size()); //Query whether there is a key or a value - contains - returns true or false System.out.println(map.containsKey("Xiao Ming")); System.out.println(map.containsValue(1)); //Traversal of map collection: //Method 1 // 1. First Set<String> keys = map.keySet();//Gets the key set of the map set map.values(); //Gets the value of the map collection // 2. Then traverse the map through the key set for (String key : keys) { System.out.println("key:"+key+",value:"+map.get(key)); //Method 2 traverses through map.entrySet() -- set < entry < string, integer > > returned by this method here Set<Entry<String, Integer>> entries = map.entrySet(); for (Entry<String, Integer> entry : entries) { System.out.println("key:"+entry.getKey()+key+",value:"+entry.getValue());; } } } }
TreeMap:
You can sort the elements in the collection according to the key - natural sorting and custom sorting
Generally, map sets are used, and overly complex objects are not used as key s
package setStudy1117; import java.util.Map; import java.util.TreeMap; public class Test05 { public static void main(String[] args) { //The natural sorting of TreeMap is dictionary sorting -- which can be understood as ASCII sorting // The number precedes the letter, and the upper case letter precedes the lower case letter Map<Integer, String> map = new TreeMap<>(); map.put(1,"a"); map.put(2,"b"); map.put(5,"c"); map.put(4,"a"); System.out.println(map);//Generally, it is sorted by key. Here, the generic type of key is Integer, so it is sorted by number Map<String, String> map1 = new TreeMap<>(); map1.put("Wangwanh","a"); map1.put("shdjsa","b"); map1.put("bjadksd","c"); map1.put("asdjk","a"); map1.put("15asdjk","a"); System.out.println(map1);//Sort here according to the first ASCII ascending order of the key } }
Tool class for manipulating Collections: collections class
Collections class is mainly used to process sets, lists, maps and other collections, such as sorting, addition, deletion, modification, query, inversion, and random disruption
package setStudy1117; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Test06 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("b"); list.add("cb"); list.add("cab"); list.add("cb"); list.add("a"); list.add("1"); System.out.println(list); //Invert list elements Collections.reverse(list); System.out.println(list); //Random disruption Collections.shuffle(list); System.out.println(list); //sort Collections.sort(list); System.out.println(list);//The default is in ascending dictionary order } }
Sort (List, Comparator): sort the elements of the List collection according to the comparison method of the Comparator object (which needs to be rewritten)
notes:
If the element in the collection is a student, the student class must implement the Comparator interface so that the student class can override the compare method.
package setStudy1117; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Test06 { public static void main(String[] args) { Student s1 = new Student(14,"Zhang San"); Student s2 = new Student(12,"Li Si"); Student s3 = new Student(16,"Wang Wu"); Student s4 = new Student(18,"Zhou Zhou"); List<Student> stus=new ArrayList<>(); stus.add(s1); stus.add(s2); stus.add(s3); stus.add(s4); //The original order in the output set for (Student student : stus) { System.out.println(student.name+":"+student.age); }System.out.println("========================"); //Sort by Collections -- sort on the original collection -- here, the compare method is rewritten to sort in ascending order by age Collections.sort(stus,new Student()); for (Student student : stus) { System.out.println(student.name+":"+student.age); } } } class Student implements Comparator<Student>{ int age; String name; public Student(){} public Student(int age,String name){ this.age=age; this.name=name; } //In ascending order of age @Override public int compare(Student o1, Student o2) { if(o1.age>o2.age)return 1; else if(o1.age<o2.age)return -1; else return 0; } }
[learn about Comparator.compare ()]