API foundation and collection Foundation (very detailed)

1. API overview and usage steps

API(Application Programming Interface), application programming interface, Java API is a programmer's dictionary. It is the description document of the class provided to us in JDK.
These classes encapsulate the underlying code implementation. We don't need how these classes are implemented, we just need to learn how to use these classes. Therefore, we can learn from Java by querying the API
And know if you use them.

API usage steps:

  1. Open help document
  2. Click display to find the index and see the input box
  3. Who are you looking for? Then enter in the input box and press enter.
  4. Look at the bag. java.lang classes do not need to import packages, others do.
  5. See the explanation of the class.
  6. Learn construction methods.
  7. Use member methods.

Popular understanding:

The so-called API refers to many classes and methods. jdk provides some ready-made classes that can be used directly. These classes are ready-made classes that are provided to us and used directly. They are all called APIs.
API document: it tells us which classes are ready-made and which methods have their own functions. This description is called API document.
The upper right corner shows that the String keyword is lowercase, and String is a class, which was written by the author of jdk.

Look at three points:

  1. Look at the package path: Java long is the package path where the class is located. Various classes provided by jdk are also in one package. There is a String class in java package and lang package. long is the abbreviation of language.
  2. Look at the construction method summary: a class cannot be used directly under normal circumstances. If you want to use it, you need to create an object according to it. new is calling the construction method. Check which one you use,
  3. See method summary: return value type, method name, parameter. You can click the method name to jump to a more detailed description.

2. Steps for using scanner

The function of Scanner class can realize keyboard input data into the program.

General usage steps of reference type:

1. Guide Package
import package path Class name;
If the target class to be used is under the same package as the current class, you can omit the package guide statement without writing.
Only Java The contents under Lang package do not need to be imported, and other packages need import statements

2. Create
Class name object name = new class name ();

3. Use
Object name Member method name ()

Get an int number entered by the keyboard: int num = sc.nextInt();
Get a string entered by the keyboard: String str = sc.next();

The code is as follows:

import java.util.Scanner;

public class Demo01Scanner{
	public static void main(String[] args){
		// 2. Create
		// Remarks: system In stands for input from the keyboard
		Scanner sc = new Scanner(System.in);
		
		// 3. Get the int number entered by the keyboard
		int num = sc.nextInt();
		System.out.println("Typed int The number is:" + num);
		
		// 4. Get the string entered by the keyboard
		String str = sc.next();
		System.out.println("The input string is:" + str);
		
	}
}

2.1 lift Li Yi (enter two numbers on the keyboard for summation)

Title:
Enter two int numbers on the keyboard and find the sum value

Idea:

  1. Since keyboard input is required, use Scanner
  2. Three steps of Scanner: package guide, creation and use
  3. You need two numbers, so you need to call the nextInt method twice
  4. When you get two numbers, you need to load them together.
  5. Print out the results

The code is as follows:

import java.util.Scanner;
public class Demo02ScannerSum{
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Please enter the first number:");
		int a = sc.nextInt();
		
		System.out.println("Please enter the second number:");
		int b = sc.nextInt();
		
		int result = a + b;
		System.out.println("The result is:" + result);
	}
}

2.2 lift Li 2 (enter three numbers on the keyboard to find the maximum value)

Title: enter three int numbers on the keyboard, and then find the maximum value

Idea:

  1. Since it is keyboard input, Scanner must be used
  2. Scanner consists of three steps: importing package, creating and using nextInt() method
  3. Since it is three numbers, call the nextInt() method three times to get three int variables
  4. It is impossible to judge which of the three numbers is the largest at the same time. It should be converted into two steps:
    4.1 first judge who is the largest in the first two and get the maximum value of the first two
    4.2 take the maximum value of the first two and compare it with the third number to get the maximum value of the three arrays
  5. Print the final result

The code is as follows:

import java.util.Scanner;
public class Demo03ScannerMax{
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Please enter the first number:");
		int a = sc.nextInt();
		System.out.println("Please enter the second number:");
		int b = sc.nextInt();
		System.out.println("Please enter the third number:");
		int c = sc.nextInt();
		
		// First, get the maximum value of the first two figures
		int temp = a > b ? a : b;
		int max = temp > c ? temp : c;
		
		System.out.println("The maximum value is:" + max);
 	}
}

3. Description of anonymous object

Standard format for creating objects:
Class name object name = new class name ();

Anonymous objects are objects that have only the right side, without the left name and assignment operator.
new class name ();
Note: anonymous objects can only be used once. You have to create a new object next time
Usage suggestion: if it is determined that an object only needs to be used once, you can use anonymous objects.

When we create objects, we always have to give a name. In some cases, the name can be omitted. Objects without a name are called anonymous objects,
Note: several new objects are created.
For an object, you only want to click through its name once. This time, you only use it once. If you choose another name, it's redundant. In this case, you can directly new objects and click who you want to use,
However, anonymous objects can only be used once. Conversely, some objects can be used only once.

public class Demo01Anoymous{
	public static void main(String[] args){
		Person one = new Person();
		one.name = "Gao Yuanyuan";
		one.showName();//My name is Gao Yuanyuan
		System.out.println("==========================");
		
		//Anonymous object
		new Person().name = "You Ting Zhao";
		new Person().showName();//My name is nall
	}
}

3.1 anonymous object as parameter and return value of method

import java.util.Scanner;

public class Demo02Anonymous{
	
	public static void main(String[] args){
		// Use the normal way
		// Scanner sc = new Scanner(System.in);
		// int num = sc.nexInt();
		
		//Anonymous objects
		//int num = new Scanner(System.in).nextInt();
		//System.out.println("input is:" + num);
		
		// Pass in parameters using general writing
		// Scanner sc = new Scanner(System.in);
		// methodParam(sc);
		
		// Use anonymous objects to pass parameters
		// methodParam(new Scanner(System.in));
		
		Scanner sc = methodReturn();
		int num = sc.nextInt();
		System.out.println("I entered:" + num);
		
	}
	
	public static void methodParam(Scanner sc){
		int num = sc.nextInt();
		System.out.println("Enter:" + num);
	}
	
	public static Scanner methodReturn(){
		// Scanner sc = new Scanner(System.in);
		// return sc;
		
		return new Scanner(System.in);
	}
}

4. Random overview and basic usage

The Random class is used to generate Random numbers. It is also used in three steps,

  1. Guide Package
    import java.util.Random

  2. establish
    Random r = new Random;// Just leave the parentheses blank

  3. use
    (1) Get a random int number (the range is all ranges of int, with positive and negative), int num = r.nextInt()
    (2) Get a random int number (the parameter represents the range of, left closed right open interval), int num = r.nextInt(3)
    In fact, the meaning of representation is: [0,3), that is, 0-2

public class Demo01Random{
	public static void main(String[] args){
		// Without parameters
		Random r = new Random();
		int num  = r.nextInt();
		System.out.println("The random number is:" + num);
		
		// With parameters, 10 cycles
		
		for(int i = 0; i < 10; i++){
			int a = r.nextInt(2);
			System.out.println(a);
		}
	}
}

4.1 Ju Li Yi (generate random numbers between 1-n)

Title Requirements:
According to the value of int variable n, obtain the random number. The range is [1,n]. You can get 1 or n

Idea:
1. Define an int variable
2. To use Random, a single step is to guide, create and use the package
3. If you write 10, it is 0-9. However, you want 1-9. You can find that the whole + 1.
4. Print random numbers

public class Demo02Random{
	public static void main(String[] args){
		int n = 5 ;
		Random r = new Random();
		
		// With parameters, 10 cycles
		
		for(int i = 0; i < 10; i++){
			int num = r.nextInt(n) + 1 ;
			System.out.println(num);
		}
	}
}

4.2 Ju Li Er (guessing numbers)

Title: code analog guessing game

Idea:

  1. First, you need to generate a Random number, and once it is generated, it will not change any more, use Random's nextInt method
  2. Keyboard input is required, so Scanner is used
  3. Get the number entered by the keyboard, and use the nextInt method in the Scnaner method
  4. Two numbers have been obtained. Judge (if)
    If it is too large, the prompt is too large and try again
    If it is too small, the prompt is too small and try again
    If you guess right, the game is over
  5. Try again is to try again. If the number of cycles is uncertain, use while (true).
import java.util.Random;
import java.util.Scanner;

public class Demo03RandomGame{
	public static void main(String[] args){
		Random r = new Random();
		int randomunm = r.nextInt(100) + 1; // [1,100]
		Scanner sc = new Scanner(System.in);
		
		while(true){
			System.out.println("Please enter the number you guessed");
			int guessNum = sc.nextInt(); // Enter the guessed number on the keyboard
		
			if(guessNum > randomunm){
				System.out.println("It's too big. Please try again");
			}else if(guessNum < randomunm){
				System.out.println("Too small, please try again");
			}else{
				System.out.println("Congratulations, you guessed right");
				break;
			}
		}
	}
}	

5. Object array

Title: define an array to store three Person objects
One disadvantage of arrays is that once they are created, the length cannot be changed during the running of the program

public class Persons{
	
	private String name;
	private int age;
	
	public Persons(){
		
	}
	public Persons(String name,int age){
		this.name = name;
		this.age = age ;
	}
	
	public void setName(String name){
		this.name = name;
		
	}
	public String getName(){
		return name;
	}
	public void setAge(int age){
		this.age = age;
	}
	public int getAge(){
		return age;
	}
}
public class Demo04Array{
	public static void main(String[] args){
		// First, create an array with a length of 3, which is used to store objects of type Person
		Persons[] array = new Persons[3];
		
		Persons one = new Persons("Delireba",18);
		Persons two = new Persons("Gulinaza",20);
		Persons three = new Persons("Ma erzaha",30);
		
		//Assign the address value in one to the position of element 0 of the array
		array[0] = one;
		array[1] = two;
		array[2] = three;
		
		System.out.println(array[0]); //Address value
		System.out.println(array[1]);
		System.out.println(array[2]);
		
		System.out.println(array[0].getName() + "Age:"+ array[0].getAge() + "year");//Delireba
		
	}
}

6. ArrayList set overview and basic usage

java.util.ArrayList: this class needs to be import ed and used later
, representing a specified data type, called a generic type. E. Taken from the initial of Element. Where e appears again, we can replace it with a reference data type, indicating which reference type elements we will store.
In the angle brackets are generics

ArrayList can also store multiple data. What type of data is unified? The type is written in angle brackets.
The most commonly used is nonparametric construction

Why isn't an address value returned?
The person who wrote the ArrayList made a special treatment on the ArrayList class. How to deal with it? After that, I will learn the tostring method.

The length of the array cannot be changed
However, the length of the ArrayList set can be changed at will

For ArrayList, there is an angle bracket for generics
Generics, that is, all elements in the collection, are of the same type
Note: generic types can only be reference types, not basic types.

matters needing attention:
For the ArrayList set, what is printed directly is not the address value, but the content

If the content is empty, you will get empty brackets []
alt + enter (local)

import java.util.ArrayList;
public class Demo05ArrayList{
	public static void main(String[] args){
		//An ArrayList collection is created. The name of the collection is list, which contains all the data of String type
		//Note: starting from JDK 1.7, no content can be written inside the angle brackets on the right, but < > the province still needs to write.
		
		ArrayList<String> list = new ArrayList<>();
		System.out.println(list);
		
		// To add some data to the collection, you need to use the add method
		list.add("Zhao Liying");
		System.out.println(list);
		list.add("Delireba");
		list.add("Gulinaza");
		list.add("Ma erzaha");
		System.out.println(list);
//		list.add(100);// Wrong way of writing, because the angle bracket generic has said that it is a string when it is created, and the elements added must be all strings

6.1 common methods and traversal of ArrayList set

Array length
Set list size()
list.fori = for(int i = 0 ; i < list.size() ; i++){}
sout

Common methods in ArrayList are:

Public Boolean add (E, e): add elements to the collection. The type of parameters is consistent with the generic type
Note: for ArrayList collection, the add action must be successful, so the return value can be used or not.
However, for other sets (future learning), the add action may not be successful.

public E get(int index): get the element from the collection. The parameter is the index number, and the return value is the element at the corresponding position.
public E remove(int index): deletes an element from the collection. The parameter is the index number, and the return value is the deleted element.
public int size(): gets the size and length of the collection. The return value is the number of elements contained in the collection.

Take chestnuts for example:

import java.util.ArrayList;

public class Demo06ArrayListMethod{
	public static void main(String[] args){
		ArrayList<String> list = new ArrayList<>();
		System.out.println(list); // []
		
		boolean success = list.add("Liuyan");
		System.out.println(list);
		System.out.println("Whether the added action is successful:" + success);
		
		list.add("Gao Yuanyuan");
		list.add("You Ting Zhao");
		list.add("Li Xiaolu");
		list.add("Jia Nailiang");
		System.out.println(list);//[Liu Yan, Gao Yuanyuan, Zhao Youting, Li Xiaolu, Jia Nailiang]
		
		//Get element from collection, get. The index value starts at 0
		System.out.println("======================");
		String name = list.get(2);
		System.out.println("Second index position:" + name);
		
		//To remove an element from the collection, remove. Index values start at 0.
		System.out.println("======================");
		String whoRemoved = list.remove(3);
		System.out.println("Who was deleted:" + whoRemoved);
		System.out.println(list);
		
		//Get the length dimension of the collection, that is, the number of elements in it
		System.out.println("======================");
		int size = list.size();
		System.out.println("The length of the set is:" + size);
		
		//Traversal set
		System.out.println("======================");
		System.out.println("Traversal set:");
		for(int i = 0; i < size; i++){
			System.out.println(list.get(i));
		}
	}
}

6.2 the ArrayList set stores basic data types

Why can't it be the basic type?? All the data stored in the collection are address values, but the basic type of data has no address value, so it is not allowed to store an int in it.
There are solutions:

If you want to summarize and store basic type data like the collection ArrayList, you must use the "wrapper class" corresponding to the basic type

Basic type Wrapper classes (reference types and wrapper classes are all under the java.lang package)
byte              Byte
short             Short
int                 Integer [Special]
long              Long
float              Float
double          Double
char Character [Special]
boolean        Boolean

Tip:
Starting from JDK 1.5, it supports automatic packing and unpacking.

Auto packing: basic type -- > packing type
Automatic unpacking: package type -- > basic type

This process does not require manual intervention and is completed automatically.

The example code is as follows:

import java.util.ArrayList;

public class Demo07ArrayListBsic{
	public static void main(String[] args){
		//Wrong writing! A generic type can only be a reference type, not a base type
	    // ArrayList<int> listC = new ArrayList<>();
		
		ArrayList<Integer> listC = new ArrayList<>();
		listC.add(100);
		listC.add(200);
		System.out.println(listC);//[100,200]
		
		int num = listC.get(1);
		System.out.println("Element 1 is:" + num);
	}
}

6.3 Ju Li Yi (storing random numbers)

Title: generate 6 random integers between 1-33, add them to the set, and traverse the set

Idea:

  1. You need to store 6 numbers to create a collection
  2. Random is needed to generate random numbers
  3. Loop 6 times to generate 6 random numbers, for loop
  4. Call r.nextInt(int n) in the loop. The parameters are 33, 0-32, and the whole + 1 is 1-33
  5. Add a number to the set: add
  6. Traversal collection: for, size, get

The code is as follows:

import java.util.Random;
import java.util.ArrayList;
public class Demo01ArrayListRandom{
	public static void main(String[] args){
		ArrayList<Integer> list = new ArrayList<>();
		Random r = new Random();
		for(int i = 0; i < 6 ; i++){
			int num = r.nextInt(33)+1;
			list.add(num);
		}
		for(int i = 0; i < list.size();i++){
			System.out.println(list.get(i));
		}
	}
}

IDEA shortcut:

6.fori = for(int i = 0 ; i < 6 ; i++)
list.fori = for (int i = 0 ; i < list.size ; i++)
biglist.fori = for (int i = 0 ; i < biglist.size; i++)

6.4 example 2 (storing custom objects)

Title:
Customize 4 student objects, add to the collection, and traverse
Idea:

  1. Custom Student class, four parts
  2. Create a collection to store student objects, generic:
  3. Create four student objects based on the class
  4. Add 4 students to the set, add
  5. Traversal collection: for, size, get

The code is as follows:

public class  Student{
	private String name;
	private int age;
	
	public Student(){
		
	}
	
	public Student(String name , int age ){
		this.name = name;
		this.age = age;
	}
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
		
	}
	public void setAge(int age){
		this.name = name;
		
	}
	public int getAge(){
		return age;
	}
}
import java.util.ArrayList;

public class Demo01ArrayListStudent{
	public static void main(String[] args){
		ArrayList<Student> list = new ArrayList<>();
		
		Student one = new Student("Guo Yang",20);
		Student two = new Student("Huang Rong",21);
		Student three = new Student("Guo Jing",23);
		Student four = new Student("duan yu",25);
		
		list.add(one);
		list.add(two);
		list.add(three);
		list.add(four);
		System.out.println(list); //The output is the address value
		for(int i = 0; i < list.size(); i++){
			Student stu = list.get(i);
			System.out.println("full name:" + stu.getName() + ", Age" + stu.getAge());
		}
	}
}

6.5 Ju Li San (traversing the set string according to the specified format)

When a set is used as a method parameter, the received parameter is an address value, and then the address value can be used for operation.

Title:
Defines the method of printing the set in the specified format (with the ArrayList type as the parameter), encloses the set with {} and separates each element with @.
Format reference {element @ element @ element}

give an example:
System.out.println(list); [10,20,30]
printArray(list); {10@20@30}

The code is as follows:

import java.util.ArrayList;

public class Demo03ArrayListPrint{
	public static void main(String[] args){
		ArrayList<String> list = new ArrayList<>();
		
		list.add("Dagu");
		list.add("Lina");
		list.add("New town");
		list.add("Wild Rui");
		
		System.out.println(list);
		
		printArrayList(list);
	}
	/*
	Three elements of defining methods
	Return value type: it is only for printing. There is no operation and no result, so void is used
	Method name: printArrayList
	Parameter list: ArrayList
	*/
	public static void printArrayList(ArrayList<String> list){
		// To print out this form {Dagu @ Lina @ Xincheng @ yerui}
		System.out.print("{");
		for(int i =0 ; i < list.size(); i++){
			String name = list.get(i);
			if(i == list.size() - 1){
			System.out.print(name + "}");
			}else{
				System.out.print(name + "@");
			}
			
		}
	}
}

6.6 Ju Li IV (random number in the filter set)

Title:
Use a large set to store 20 random numbers, then filter the even elements and put them into a small set.
It is required to use custom methods to implement filtering

analysis:

  1. You need to create a large collection to store int numbers,
  2. Random nextInt is used for random numbers
  3. Loop 20 times, put random numbers into a large set, and use the for loop and add methods
  4. Define a method for line filtering
    Filter: filter the elements that meet the requirements according to the large set to get a small set.
  5. Judge whether (if) is even: num% 2 = = 0
  6. If it is even, put it in the small set, otherwise don't put it

Three elements of the method:

Return value type: ArrayList small collection (the number of elements in it is uncertain)
Method name: getSmallList
Parameter list: large collection of ArrayList (containing 20 random numbers)

The code is as follows:

import java.util.ArrayList;
import java.util.Random;

public class Demo04ArrayListReturn{
	public static void main(String[] args){
		ArrayList<Integer> biglist = new ArrayList<>();
		Random r = new Random();
		for(int i = 0 ; i < 20; i++){
			int num = r.nextInt(100)+1; // [1,100]
			biglist.add(num);
		}
		// System.out.println(biglist);
		
		ArrayList<Integer> smalllist = getSmallList(biglist);
		
		System.out.println("Number of even numbers:" + smalllist.size());
		
		for(int i = 0 ; i < smalllist.size() ; i++){
			System.out.println(smalllist.get(i));
		}
	}
	
	public static ArrayList<Integer> getSmallList(ArrayList<Integer> biglist){
		ArrayList<Integer> smalllist = new ArrayList<>();
		for(int i = 0 ; i < biglist.size(); i++){
			if(biglist.get(i)%2 == 0){
				smalllist.add(biglist.get(i));
			}
		}
		return smalllist;
	}
}

Tags: Java api arraylist

Posted by mark_h_uk on Sun, 22 May 2022 18:36:01 +0300