The most detailed Java API exercises and collection notes in the whole network

Java related API exercises

Integer

Introduction to this class: Integer: located in Java Lang package
This class is the wrapper class of basic data type int, and introduces the main methods of this class

  1. Integer(int/String), a construction method, which puts integers or strings into and packages them into integer objects, also known as "boxing"
  2. valueOf(), a static method that wraps integers into Integer objects
  3. intValue() returns the integer value of the object, which is called "unpacking"
  4. static int parseInt(String s), which converts a string to an integer of type int and returns
		//Create an Integer wrapper class object and put it into parameter 12, which is automatically boxed
        Integer i1 = new Integer(12);
        System.out.println(i1);//Output 12
        //Create an Integer wrapper class object and put it into the String type parameter 12, which is automatically boxed
        Integer i2 = new Integer("12");
        System.out.println(i2);
        //Output 234, manual packing
        System.out.println(Integer.valueOf(234));
        //Unpack and convert Integer packing class object to int basic data type
        int i3 = i1;
        //Output 12
        System.out.println(i3);
        //Resolve string 1234 to type int, provided that the incoming string can be converted to type int
        int i4 = Integer.parseInt("1234");

String

The String class is located in Java Lang package, String class is used to encapsulate String sequence
Common methods of String class:

  1. contains() to determine whether the string contains something
  2. charAt(), returns the character of the corresponding position according to the subscript specified by the parameter
  3. int length(), returns the length of the string
  4. boolean equals(Object o) is used to judge whether the call string and parameter string are equal. It overrides the equals method of Object class
  5. Judge whether the case of isboolean string is equal, but ignore the case of isboolean string
  6. boolean endsWith(String suffix) to judge whether the current string ends with suffix
  7. boolean startWith(String prefix) to judge whether the current string starts with prefix
  8. String toLowerCase(), convert all call strings to lowercase
  9. String toUpperCase(), convert all call strings to uppercase
  10. String trim(), clear the blank characters on both sides
  11. int indexOf(String str) returns the subscript position of the first occurrence of the incoming string. If it does not exist, it returns - 1
  12. int lastIndexOf(String str) returns the position of the last occurrence of the incoming string. If it does not exist, it returns - 1
  13. String substring(int beginIndex) intercepts all characters from beginIndex to the end of the string and returns
  14. String substring(int beginIndex, int lastIndex), which intercepts the characters from the beginning of beginIndex (including the start character) to the end of lastIndex (excluding the end position) and returns
  15. valueOf(int i) converts int type to String string
    Code demonstration:
		//Create string object and assign value
		String str = " this is a test of java ";
		//Clear the blank characters on both sides of str string
		System.out.println("take str Empty white space characters on both sides of the string:" + str.trim());
		//Find whether this exists in str string
		System.out.println("str Does the string exist this: : " + str.contains("this"));
		//Find what character is the 5 subscript
		System.out.println("str The characters with subscript 5 in the string are:" + str.charAt(5));
		//Return string length
		System.out.println("str String length:" + str.length());
		//Judge whether str string is equal to This Is a Test Of Java
		String equStr = "This Is a Test Of Java";
		System.out.println("str Does the string match This Is a Test Of Java equal::" + str.equals(equStr));
		//Judge whether str string is equal to This Is a Test Of Java
		System.out.println("Ignore case judgment str Does the string match This Is a Test Of Java equal::" + str.equalsIgnoreCase(equStr));
		//Determine whether the str string ends with a
		System.out.println("str Whether the string is in a ending::" + str.endsWith("a"));
		//Does the str string start with a
		System.out.println("str Whether the string is in a start::" + str.startsWith("a"));
		//Convert str string to lowercase
		System.out.println("take str String to lowercase:" + str.toLowerCase());
		//Convert str string to uppercase
		System.out.println("take str Convert string to uppercase:" + str.toUpperCase());
		//Find the first position of a in str string
		System.out.println("str Find in string a First position:" + str.indexOf("a"));
		//Find the last position of a in str string
		System.out.println("str Find in string a Last location:" + str.lastIndexOf("a"));
		//Intercept the str string from 1 to the last. Because the first one is a space, it is the whole content
		System.out.println("intercept str String from 1 to the last string:" + str.substring(1));
		//Intercept the str string from 3 to 8
		System.out.println("intercept str String from 3 to 8. Last string:" + str.substring(3, 8));
		//Convert numbers to strings
		System.out.println("Convert numbers to Strings:" + str.valueOf(3244));

String buffer class

Why is there a String buffer class? Because the String class is a fixed value and cannot be modified once it is created, as shown in the figure, the source code of OracleJavaString class:

The objects created by the String source code definition are final and cannot be modified. If you want to modify the String class, create a new object and assign the old value to the new object. The old object still occupies space and is assigned to the new object again. Therefore, the String buffer class is introduced, which can modify the String and modify it in this object.

StringBuffer&StringBuilder

Both classes are located in Java Lang package

Similarities and differences between the two:
Similarities: both are used to describe variable character sequences
Differences: the StringBuffer class is provided in the early stage and supports thread safety, but it is inefficient. The StringBuilder class is provided in the later stage and does not support thread safety. It is highly efficient. It is recommended to use this class
Introduction: there is basically no difference between the two class methods:

  1. java.lang.StringBuilder(String str), a parameterized construction method, modifies variable string objects according to parameters
  2. int capacity(), used to get the capacity of the calling object and return. The initial capacity is string length + 16
  3. int length(), used to obtain the length (number of characters) and return
  4. StringBuilder insert(int offset, String str), insert str string at offset position
  5. StringBuilder append(String str), append string after source string
  6. StringBuilder delete(int start, int end) to delete the string from start to end
  7. StringBuilder replace(int start, int end, String str) replaces the contents from start to end with str string
  8. StringBuilder reverse(), inverting the source string
    Code demonstration
		//Initialize the StringBuilder class and put the parameters into
		StringBuilder sbf = new StringBuilder("this is a java");
		System.out.println("sbf The contents are:" + sbf);
		//Get sbf object capacity
		System.out.println("obtain sb Object capacity:" + sbf.capacity());
		//Gets the length of the sbf object content
		System.out.println("obtain sbf Length of object content:" + sbf.length());
		//Inserts a string at the specified location
		System.out.println("Inserts a string at the specified location:" + sbf.insert(8, "of "));
		//Append string after source string
		System.out.println("Append string after source string:" + sbf.append("!!"));
		//Delete content from start position to end position
		System.out.println("Delete content from start position to end position:" + sbf.delete(5, 7));
		//Replace the content from the starting position to the borrowing position with the specified content
		System.out.println("Replace the content from the starting position to the borrowing position with the specified content:" + sbf.replace(5, 8, "is!"));
		//Invert source string
		System.out.println("Invert source string:" + sbf.reverse());

Date

The Date.java class is located in Util package, used to operate the Date
Introduce the common methods of Date class:
Date(), a parameterless construction method to obtain the current date object (accurate to milliseconds, 1000 milliseconds = 1 second)
Date(time), a parameterized construction method, obtains the corresponding date object according to the time parameter
getTime(), get the number of milliseconds from 1970 to the current
setTime(long time) to set the specified number of milliseconds
Code demonstration

		//Initialize date object
		Date date = new Date();
		//Output current date
		System.out.println(date);
		//Initializes the date2 object and sets the number of milliseconds
		Date date2 = new Date(21324354657643L);
		System.out.println(date2);
		//Gets the number of milliseconds from 1970 to the present
		System.out.println(date.getTime());
		//Set milliseconds
		date.setTime(12343543423L);
		System.out.println(date);

SimpleDateFormat

This class is mainly used to format date objects
Such methods are as follows:

  1. SimepleDateFormat(pattrn) has a parameter construction method, which formats the date according to the format of the parameter y: year M: month d: Date h: hour M: minute s: second
  2. Format (date) format, which formats the date object as a string
  3. parse() parses the string into a date object
		//Initialization Date object
		Date date = new Date();
		//Initialize format date object
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		//Parse the date object into a string
		System.out.println(sdf.format(date));
		//Parse string into Date object
		String str = "2020-04-12 13:23:33";
		Date date2 = null;
		//Catch exception
		try {
			date2 = sdf.parse(str);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//Parse the date object into a string again
		System.out.println(sdf.format(date2));

Calendar

Calendar class is a calendar class, which encapsulates all possible time information into static member variables for easy access
Acquisition method:
Calendar is an abstract class, so it cannot be instantiated. The static method getInstance() of the initialization object is specified internally, and a calendar is obtained using the default time zone and locale
Common methods:

  1. get(int field) returns the value of the field for a given calendar.
  2. set(int field, int value) to set the given calendar field to the given value
  3. add(int field, int amount) adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar
  4. getTime(), returns a number of milliseconds indicating this Calendar

Code demonstration:

		//Initialize the Calendar class, create the object mode, and call the static method to realize the instantiation
		Calendar cal = Calendar.getInstance();
		//Outputs the year of the current date
		System.out.println(cal.get(Calendar.YEAR));
		//Set the current year to 2020
		cal.set(Calendar.YEAR, 2020);
		System.out.println(cal.get(Calendar.YEAR));
		//Add year 2 to 2022
		cal.add(Calendar.YEAR, 2);
		System.out.println(cal.get(Calendar.YEAR));
		//Returns the current number of milliseconds
		System.out.println(cal.getTime());
		//Format date object
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day hh Time mm branch ss second");
		//Assign the formatted Date object to str
		String str = sdf.format(cal.getTime());
		System.out.println(str);

Set exercise

Collection collection

Collection is the highest-level interface. Its subclasses include List and Set interfaces
The most basic unit of a Collection is a single character
Because Collection is an interface, all methods that live in Collection can be called in subclasses
Describes the methods of the Collection interface:

  1. boolean isEmpty() determines whether the current collection is empty
  2. int size() gets the length of the collection content
  3. Boolean add (E) to add elements of the specified type to the collection
  4. boolean addAll(Collection col) to add all the contents of the specified collection to the collection
  5. Boolean remove (E) to delete the specified element in the collection
  6. removeAll(Collection c) to delete a collection of the specified type
  7. void clear(), clear the current collection
  8. boolean contains(Object o) to judge whether the current object exists in the collection
  9. boolean containsAll(Collection c) to judge whether the current collection exists in a collection
    Code demonstration Collection method:
		Collection<String> col = new ArrayList<String>();
		//Adds the specified element to the collection
		col.add("a");
		col.add("b");
		col.add("c");
		col.add("d");
		//Judge whether the current collection is empty
		System.out.println("Judge whether the current collection is empty:" + col.isEmpty());
		//Gets the length of the collection content
		System.out.println("Get the length of the collection content:" + col.size());
		//Adds the entire contents of the specified collection to the collection
		Collection<String> col2 = new ArrayList<>();
		col2.add("e");
		col2.add("f");
		col2.add("j");
		col.addAll(col2);
		System.out.println("Directional set col Add in col2 All contents of the collection" + col);
		//Delete the j element in the collection
		col.remove("j");
		System.out.println("Delete from collection j Element:" + col);
		//Delete col2 set
		col.removeAll(col2);
		System.out.println("delete col2 Set:" + col);
		//Empty current collection
		col.clear();
		System.out.println("Empty current collection col Content:" + col);
		//Determine whether the element in col set exists
		System.out.println("judge col Elements in collection a Is there:" + col.contains("a"));
		//Whether col1 exists in the set
		System.out.println("judge col2 Does the collection exist col1 In the collection:" + col.containsAll(col2));

generic paradigm

At present, although different types can be stored in the collection, the reason is that all types of elements are packaged as Object types, but when taken from the collection, it must be reduced to type conversion. The process is cumbersome, and conversion exceptions may occur during conversion

In order to avoid the above errors, from jdk1 5. At the beginning, the generic mechanism was added, which greatly facilitates the development of programs and reduces the occurrence of exceptions,
Syntax format:
Set interface / implementation class < reference data type > = new set implementation class < reference data type > ();
List< Person > list = new ArrayList< Person >();
It is explicitly specified that only Person type data can be saved. When obtaining and fetching data, only Person type data can be fetched, and forced type conversion is no longer used.

List

List is an interface under Collection, which is mainly used for linear table data structure. It is the indirect parent class of ArrayList and LinkedList. In addition to the methods inherited from the Collection collection, the list Collection adds some methods to operate the Collection elements according to the index.

  1. void add(int index, Object ele): inserts an ele element at the index position
  2. Object get(int index): get the element at the specified index position
  3. int indexOf(Object obj): returns the position where obj first appears in the collection
  4. int lastIndexOf(Object obj): returns the last occurrence of obj in the current collection
  5. Remove the index of the object and return the index of this element
  6. Object set(int index, Object ele): sets the element of the specified index position to ele
		List<String> list1 = new ArrayList<String>();
		list1.add("a");
		list1.add("b");
		list1.add("d");
		list1.add("e");
		list1.add("b");
		//Add element at specified position
		list1.add(2,"c");
		System.out.println("Add an element at the specified position:" + list1);
		//Get the specified target
		System.out.println("Get the specified target:" + list1.get(2));
		//Gets the position where b first appears in the collection
		System.out.println("obtain b First occurrence in the collection:" + list1.indexOf("b"));
		//Gets the location of the last occurrence of b in the collection
		System.out.println("obtain b Last occurrence in the collection:" + list1.lastIndexOf("b"));
		//Removes the specified element
		list1.remove(2);
		System.out.println("Remove the specified element:" + list1);
		//Sets the specified location to the specified element
		list1.set(2, "C");
		System.out.println("Set the specified location to the specified element:" + list1);
ArrayList

This class implements the List interface, which is characterized by fast query and fast loop traversal. The disadvantage is that the insertion and deletion efficiency is not high.

LinkdeList

This class implements the List interface, which is characterized by fast insertion, deletion and slow loop traversal.
LinkdedList: a two-way linked list. It does not declare an array inside, but defines the first and last of Node types, which are used to record the first and last elements
Summary: the methods of ArrayList and LinkedList are the same in logic, except for the difference in performance. ArrayList is more suitable for random access and traversal of elements, and LinkedList is more suitable for deleting and inserting elements. This difference can be ignored when the performance requirements are not very high.

Set

The Set Collection is located in Java Util package is a sub interface of Collection. The feature is that elements cannot be repeated. This interface mainly implements classes: HashSet and TreeSet
The bottom layer of HashSet class is a hash table implementation, which is stored in hash and out of order
The bottom layer of TreeSet class is realized by a binary tree, which is stored in order

The set set cannot contain the same elements. If you try to add two identical elements to the same set set, the add operation fails. Set determines whether two objects are the same, not using the = = operator, but according to the equals() method.

HashSet

HashSet stores the elements in the set according to the Hash algorithm, so it has good performance of access, search and deletion. HashSet has the following characteristics:

  1. The order of elements cannot be guaranteed
  2. HashSet is thread unsafe
  3. Collection elements can be null

The bottom layer of HashSet is also an array, with an initial capacity of 16.
Code example:

	Set<Integer> haset = new HashSet<>();
		haset.add(1);
		haset.add(3);
		haset.add(2);
		haset.add(4);
		haset.add(66);
		//Add 66 again
		haset.add(66);
		System.out.println(haset);


It can be seen that the HashSet is out of order and the data cannot be repeated.

TreeSet

TreeSet is orderly and non repeatable. The bottom layer of this kind is realized by binary tree and arranged in order. See the example
Natural sorting:
Title: the existing Person class, attribute Id, uses natural sorting to realize sorting

import java.util.Set;
import java.util.TreeSet;

/*Implement the Comparable interface to sort*/
public class Person implements Comparable<Person>{

	String name;
	int id;
	
	/**
	 * Parameterized construction method, initialization information
	 * @param name
	 * @param id
	 */
	public Person(String name, int id) {
		this.name = name;
		this.id = id;
	}
	
	public static void main(String[] args) {
		TreeSet<Person> treset = new TreeSet<Person>();
		treset.add(new Person("Zhang San", 12));
		treset.add(new Person("Li Si", 13));
		treset.add(new Person("Wang Wu", 14));
		treset.add(new Person("Zhao Liu", 15));
		System.out.println(treset);
	}
	
	@Override
	public int compareTo(Person o) {
		return id > o.id ? 1 : -1;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return name + "," + id;
	}
}

Custom sorting:
If you are the same age, sort by name

public class Person implements Comparable<Person>{

	String name;
	int age;
	
	public Person(String name, int age) {
		// TODO Auto-generated constructor stub
		this.name = name;
		this.age = age;
	}
	
	public static void main(String[] args) {
		TreeSet<Person> treset = new TreeSet<>();
		treset.add(new Person("Zhang San", 22));
		treset.add(new Person("Li Si", 22));
		treset.add(new Person("Wang Wu", 26));
		treset.add(new Person("Zhao Liu", 25));
		treset.add(new Person("Feng Qi", 33));
		treset.add(new Person("A Li Si", 22));
		System.out.println(treset);
	}
	
	/**
	 * User defined sorting. Now sort by age. If the age is the same, sort by name dictionary order
	 */
	@Override
	public int compareTo(Person o) {
		// TODO Auto-generated method stub
		if (age != o.age) {
			return age > o.age ? 1 : -1;
		} else {
			return name.compareTo(o.name);
		}
	}
	
	/**
	 * Override toString method
	 */
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return name + "," + age;
	}
}

Map collection

Java. util. The map (k, V) interface is used to store a set in the form of key value pairs (key = > value). Keys cannot be repeated, and a key can only correspond to one value:
Common implementation classes of Map interface:
HashMap, HashMap, and hashedproperties.

Among them, HashMap is the most frequently used implementation class of Map interface
HashMap is stored in hash table at the bottom
TreeMap is stored in red black tree at the bottom
Common methods of Map collection: put and get
Addition, deletion and modification:
Object put(Object key,Object value): adds (or modifies) the specified key value to the current map set
void putAll(Map m): store all key value pairs in m into the current map
Object remove(Object key): removes the key value pair of the specified key and returns value
void clear(): clear all data in the current map

Query operation:
boolean isEmpty() - used to judge whether the current collection is empty.
int size() - used to get the number of key value pairs in the current collection.
Object get(Object key): get the value corresponding to the specified key
boolean containsKey(Object key): whether the specified key is included
boolean containsValue(Object value): whether the specified value is included

Method of metaview operation:
Set keySet(): returns the set set composed of all keys
Collection values(): returns the collection set composed of all values
Set entrySet(): returns the set set / view composed of all key value pairs
K getKey() - used to obtain the key value in the current element.
V getValue() - used to get the value value in the current element.
Code demonstration:

TreeMap

The bottom layer of TreeMap is realized by red black tree with orderly elements, which is similar to TreeSet in set set. The bottom layer of TreeSet is likely to be realized by TreeMap.

HashMap

Hash table is adopted at the bottom of HashMap, and the elements are out of order, but the HashMap key cannot be repeated,
Use the contains method to determine whether the key is repeated

		Map<String, String> map = new HashMap<String, String>();
		map.put("1001", "Zhang San");
		map.put("1002", "Li Si");
		map.put("1003", "Wang Wu");
		System.out.println(map);

From this code, we can see that the Map key cannot be repeated. If it is repeated, replace the value corresponding to the key
The key of HashMap is the implementation class HashSet in the Set set, and the underlying implementation of HashSet is Map, so HashMap supports the conversion of keys into HashSet.
Use iterator to traverse HashMap:

		Map<String, String> map = new HashMap<String, String>();
		map.put("1001", "Zhang San");
		map.put("1002", "Li Si");
		map.put("1003", "Wang Wu");
		map.put("1002", "Zhao Liu");
		//Find the value of the object based on the key name
		System.out.println(map.get("1001"));
		
		//Determine whether the key name 1003 is included in the set
		System.out.println(map.containsKey("1003"));
		//entrySet() converts the map set into a set view and returns
		//entry refers to a key value pair. The whole of name=value becomes a key value pair
		Set<Entry<String, String>> set = map.entrySet();
		//foreach loop traversal
		for (Entry<String, String> entry : set) {
			System.out.print(entry.getKey() + ",");
			System.out.println(entry.getValue());
		}
		//Get only the key name of the map collection
		Set<String> set2 = map.keySet();
		System.out.println(set2);
		for (String str : set2) {
			System.out.println(str);
			//The map set gets the value according to the key name
			System.out.println(map.get(str));
		}

ok, that's the end of the notes and the Java foundation. The blogger will constantly update the next chapter. It's not easy to make. I hope you can support it, 💕💕💕💕🤞🤞

Keywords: Java

Added by Ethan28 on Wed, 09 Feb 2022 21:27:28 +0200