Java Foundation series articles - reference data types of data types
Java Foundation series articles - reference data types of data types
preface
This blog mainly records some understanding of Java reference data types
Tip: the following is the main content of this article. The following cases can be used for reference
1, Data type structure diagram
2, Reference data type
1. Class
Class can be regarded as a template for creating Java objects. It describes the behavior and state of a class of objects.
Understand the definition of classes in Java through the following simple class:
public class Dog { String breed; int size; String colour; int age; void eat() { } void run() { } void sleep(){ } void name(){ } }
A class can contain the following types of variables:
- Local variables: variables defined in methods, construction methods, or statement blocks are called local variables. Variable declaration and initialization are in the method. After the method ends, the variable will be destroyed automatically.
- Member variables: member variables are variables defined in the class and outside the method body. This variable is instantiated when the object is created. Member variables can be accessed by methods in a class, constructor methods, and statement blocks of a specific class.
- Class variable: class variable is also declared in the class, outside the method body, but must be declared as static type.
A class can have multiple methods. In the above example, eat(), run(), sleep() and name() are all methods of the Dog class.
1.1 construction method
Each class has a constructor. If you do not explicitly define a constructor for a class, the Java compiler will provide a default constructor for the class.
When creating an object, at least one constructor must be called. The name of the constructor must have the same name as the class. A class can have multiple constructors.
The following is an example of a construction method:
public class Nice{ public Nice(){ } public Nice(String name){ // This constructor has only one parameter: name } }
1.2 creating objects
Objects are created from classes. In Java, the keyword new is used to create a new object. Creating an object requires the following three steps:
Declaration: declare an object, including object name and object type.
Instantiation: use the keyword new to create an object.
Initialization: when using new to create an object, the constructor will be called to initialize the object.
The following is an example of creating an object:
public class Puppy{ public Puppy(String name){ //This constructor has only one parameter: name System.out.println("What's the dog's name : " + name ); } public static void main(String[] args){ // The following statement will create a supply object Puppy myPuppy = new Puppy( "tommy" ); } }
Compiling and running the above program will print the following results:
What's the dog's name : tommy
1.3 accessing instance variables and methods
Access member variables and member methods through the created object, as follows:
/* Instantiate object */ Object referenceVariable = new Constructor(); /* Accessing variables in a class */ referenceVariable.variableName; /* Accessing methods in classes */ referenceVariable.methodName();
1.4 examples
The following example shows how to access instance variables and call member methods:
public class Puppy{ int puppyAge; public Puppy(String name){ // This constructor has only one parameter: name System.out.println("What's the dog's name : " + name ); } public void setAge( int age ){ puppyAge = age; } public int getAge( ){ System.out.println("The dog's age is : " + puppyAge ); return puppyAge; } public static void main(String[] args){ /* create object */ Puppy myPuppy = new Puppy( "tommy" ); /* Set age by method */ myPuppy.setAge( 2 ); /* Call another method to get the age */ myPuppy.getAge( ); /*You can also access member variables like this */ System.out.println("Variable value : " + myPuppy.puppyAge ); } }
Compile and run the above program to produce the following results:
What's the dog's name : tommy The dog's age is : 2 Variable value : 2
1.5 source file declaration rules
In the last part of this section, we will learn the declaration rules of the source file. Pay special attention to these rules when defining multiple classes in a source file, as well as import statements and package statements.
- There can only be one public class in a source file
- A source file can have multiple non-public classes
- The name of the source file should be consistent with the class name of the public class. For example, if the class name of the public class in the source file is Employee, the source file should be named Employee java.
- If a class is defined in a package, the package statement should be on the first line of the source file.
- If the source file contains an import statement, it should be placed between the package statement and the class definition. If there is no package statement, the import statement should be at the top of the source file.
- The import statement and package statement are valid for all classes defined in the source file. You cannot declare different packages for different classes in the same source file.
Classes have several access levels, and classes are also divided into different types: abstract classes and final classes. These are described in the access control section.
In addition to the types mentioned above, Java also has some special classes, such as internal classes and anonymous classes.
1.6 Java package
Package is mainly used to classify classes and interfaces. When developing Java programs, hundreds of classes may be written, so it is necessary to classify classes and interfaces.
1.7 import statement
In Java, if you give a complete qualified name, including package name and class name, the java compiler can easily locate the source code or class. The import statement is used to provide a reasonable path so that the compiler can find a class.
For example, the following command line commands the compiler to load Java_ All classes under the installation / Java / Io path
import java.io.*;
A simple example
In this example, we create two classes: Employee and EmployeeTest.
First open the text editor and paste the following code. Note to save the file as employee java.
The Employee class has four member variables: name, age, design, and salary. This class explicitly declares a constructor that has only one parameter.
Employee.java file code:
import java.io.*; public class Employee{ String name; int age; String designation; double salary; // Constructor of Employee class public Employee(String name){ this.name = name; } // Set the value of age public void empAge(int empAge){ age = empAge; } /* Set the value of design*/ public void empDesignation(String empDesig){ designation = empDesig; } /* Set the value of salary*/ public void empSalary(double empSalary){ salary = empSalary; } /* Print information */ public void printEmployee(){ System.out.println("Name:"+ name ); System.out.println("Age:" + age ); System.out.println("Designation:" + designation ); System.out.println("Salary:" + salary); } }
Programs are executed from the main method. To run this program, you must include the main method and create an instance object.
The following gives the EmployeeTest class, which instantiates two instances of the Employee class and calls the method to set the value of the variable.
Save the following code in employeetest Java file.
EmployeeTest.java file code:
import java.io.*; public class EmployeeTest{ public static void main(String args[]){ /* Use the constructor to create two objects */ Employee empOne = new Employee("James Smith"); Employee empTwo = new Employee("Mary Anne"); // Call the member methods of these two objects empOne.empAge(26); empOne.empDesignation("Senior Software Engineer"); empOne.empSalary(1000); empOne.printEmployee(); empTwo.empAge(21); empTwo.empDesignation("Software Engineer"); empTwo.empSalary(500); empTwo.printEmployee(); } }
Compile these two files and run the EmployeeTest class. You can see the following results:
C :> javac Employee.java C :> vi EmployeeTest.java C :> javac EmployeeTest.java C :> java EmployeeTest Name:James Smith Age:26 Designation:Senior Software Engineer Salary:1000.0 Name:Mary Anne Age:21 Designation:Software Engineer Salary:500.0
1.8 class diagram
1.8.1 generalization relation (generalization)
The inheritance structure of classes in UML is: generalize and realize:
The inheritance relationship is is-a; If two objects can be represented by is-a, it is an inheritance relationship: (... Yes...)
For example, a bicycle is a car and a cat is an animal
The generalization relation is directly represented by a line with a hollow arrow; As shown in the figure below (Car and Trunck inherit from Vihical);
Note: in the final code, the generalization relationship can overlay non abstract classes;
1.8.2 realize relationship
The implementation relationship is represented by a dotted line with a hollow arrow;
For example, as an abstract concept, "mobile behavior" is used to define objects in practice; Objects can be defined only by specifying specific subclasses (flying or running) (the class "mobile behavior" is represented by abstract classes in C + +, and the concept of interface in JAVA is easier to understand)
Note: in the final code, the implementation is related to the inheritance of abstract classes;
1.8.3 aggregation relationship (aggregation)
The aggregation relationship is represented by a straight line with a centered diamond arrow, as shown in the figure, the keyboard, mouse and display screen are aggregated to the computer, or the computer is composed of keyboard, mouse and display screen;
The aggregation relationship represents the overall relationship of entity objects, which is composed of multiple components;
Different from the relationship between portfolio departments, the whole and part are not strongly dependent. Even if the whole does not exist, the part still exists; For example, it will not be revoked, the personnel disappear, and they still exist;
1.8.4 combination relationship (combination)
The combination relationship is represented by a straight line with a solid diamond. Unlike aggregation, the whole and part in the combination are strongly dependent, and the whole does not exist and the part does not exist. For example, companies and departments, companies do not exist without departments. But the company and employees belong to the aggregation relationship, because the company still has no employees.
1.8.5 Association
The relationship between them is the structure of Spring and Nature determined by different types of objects; Therefore, correlation is a kind of "strong correlation";
Indicates that there is an association between different objects. This is a static relationship, independent of the state of the running process, and can be determined at the beginning. Therefore, it can also be expressed by the association relationship of 1 to 1, many to 1 and many to many. For example, students and schools are related. A school can have many students, but a student only belongs to one school. Therefore, this is a many-to-one relationship, which can be determined before the operation starts.
For example, there is an association between bus and ticket; Students and schools are a kind of relationship;
If the association relationship is not highlighted, it indicates the default between objects; If it is particularly highlighted, the figure shows A and B, but B does not know A;
Note: in the final code, the associated object is usually the implementation form of member variables;
1.8.6 dependencies (dependencies)
It is represented by a set of dotted lines with arrow strips;
The difference between association and relationship is that it is a temporary relationship, which may occur during operation and change with operation time; The correlation also changes;
Obviously, in a sense, any structural change is a way to remain unchanged. The production should always be in our single direction and eliminate the constant;
Unlike associations, dependencies work in the running process.
Class A and class B are dependencies, which mainly take three forms:
- Class A is a local variable in class B (of a method);
- Class A is a parameter of class B method;
- Class A sends A message to class B, which affects the change of class B;
1.9 four ways to create classes
1.9.1 create object in new mode → call constructor
In this way, we can call any constructor (nonparametric and parameterized).
User user = new User();
1.9.2 create object by reflection → call constructor
Java reflection technology is one of the characteristics of Java programs. It allows running Java programs to check themselves, or "self audit", and can directly operate the internal properties of the program.
Function of reflection:
1) You can find the type of object and the methods, properties and constructors contained in the class through the reflection mechanism
2) You can create objects through reflection and access any object methods and properties
1.9.2.1 use the newInstance method of Class}
Create an object using the newInstance method of Class. This newInstance method calls the parameterless constructor to create the object.
Or the Dog Class we used before. First, the JVM uses classloader to load the Dog Class into memory, and then immediately generates an object of Class type. This object can be regarded as a model. In the future, no matter how many instances of Dog Class are created, it is generated using this model (there is only one object of Class type corresponding to a Class).
The first step of creating objects through reflection: you need to get the class object
Class clazz = Dog.class;
In this way, after the class Object is obtained, you can obtain the specific Object through the newInstance() method. It should be noted that the return value of this method is the Object type, and we need to carry out transformation
Class clazz = Dog.class; Dog dog = (Dog)clazz.newInstance();
In this way, we can create java objects through reflection. The difference between newInstance() and new is as follows:
newInstance: weak type. poor efficiency. Only parameterless constructs can be called.
new: strongly typed. Relatively efficient. Any public construct can be called.
1.9.2.2 use newInstance method of Constructor class}
Similar to the newInstance method of Class, Java lang.reflect. There is also a newInstance method in the constructor Class to create objects. We can call parameterized and private constructors through this newInstance method.
Class clazz=Dog.class; Constructor constructor=clazz.getConstructor(String.class,int.class}); Dog dog=(Dog) constructor.newInstance("xiaohei",3}); System.out.println(dog.name+" "+dog.age);
1.9.3 using clone method} → no constructor called
Whenever we call the clone method of an object, the jvm will create a new object and copy all the contents of the previous object. Creating an object with the clone method does not call any constructors.
To use the clone method, we need to implement the clonable interface and the defined clone method.
User user1 = new User(1,"dan"); User user2 = null; user2 = (User) user1.clone();
1.9.4 using deserialization} → no constructor called
- Serialization: the process of converting an object state into a format that can be maintained or transmitted. The serialized object must be implments Serializable
- Deserialization: the process of converting a stream into an object
When two processes are communicating remotely, they can send various types of data to each other. No matter what type of data, it will be transmitted on the network in the form of binary sequence. The sender needs to convert the Java object into a byte sequence, that is, a Java object sequence, before it can be transmitted on the network, that is, the serialization process; The receiver needs to restore the byte sequence to a Java object, that is, deserialization.
Call Java io. The readObject() method of the objectinputstream object.
When we serialize and deserialize an object, the jvm creates a separate object for us. When deserializing, the jvm does not call any constructors when it creates objects.
To deserialize an object, we need to make our class implement the Serializable interface
import java.io.ObjectOutputStream; import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Date; import java.lang.management.*; public class Test { //Serialize object to file public static void serialize(String fileName){ try { //Create an object output stream and output the object to a file ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(fileName)); UserInfo user=new UserInfo("renyanwei","888888",20); out.writeObject(user); //Serialize a member object out.close(); } catch (Exception x) { System.out.println(x.toString()); } } //Deserialize from file to object public static void deserialize(String fileName){ try { //Create an object input stream to read objects from a file ObjectInputStream in=new ObjectInputStream(new FileInputStream(fileName)); //Read the UserInfo object and call its toString() method UserInfo user=(UserInfo)(in.readObject()); System.out.println(user.toString()); in.close(); } catch (Exception x) { System.out.println(x.toString()); } } public static void main(String[] args) { serialize("D:\\test.txt"); System.out.println("Serialization complete"); deserialize("D:\\test.txt"); System.out.println("Deserialization complete"); } }
2. Interface
2.1 what is an interface?
The interface in Java defines a reference type to create an abstract concept. Interfaces are implemented by classes to provide an implementation of the concept.
Before Java 8, an interface could only contain abstract methods. Java 8 allows interfaces to have static and default methods implemented.
Interfaces define relationships between unrelated classes through abstract concepts.
For example, we can create a Person class to represent a Person, and we can create a Dog class to represent a Dog.
Both man and dog can walk. Walking here is an abstract concept. Dogs can walk, and so can people. Here, we can create an interface called Walkable to represent the concept of walk. Then we can have Person class and dog class to implement Walkable concept and provide our own implementation. The Person class implements the Walkable interface and enables people to walk in a human way. Dog class can implement Walkable interface to make dogs walk in the way of dogs.
2.2 similarities between interfaces and classes
- An interface can have multiple methods.
- The interface file is saved in In the file ending in java, the file name uses the interface name.
- The bytecode file of the interface is saved in class.
- The bytecode file corresponding to the interface must be in the directory structure matching the package name.
2.3 differences between interfaces and classes
- Interfaces cannot be used to instantiate objects.
- Interface has no constructor.
- All methods in the interface must be abstract methods. After Java 8, you can use the default keyword to modify non abstract methods in the interface.
- An interface cannot contain member variables except static and final variables.
- The interface is not inherited by the class, but implemented by the class.
- The interface supports multiple inheritance.
2.4 interface characteristics
- Each method in the interface is also implicitly abstract. The methods in the interface will be implicitly specified as public abstract (only public abstract, and other modifiers will report errors).
- The interface can contain variables, but the variables in the interface will be implicitly specified as public static final variables (and can only be public. Modifying with private will report compilation errors).
- The methods in the interface cannot be implemented in the interface. The methods in the interface can only be implemented by the class that implements the interface.
2.5 differences between abstract classes and interfaces
- Methods in abstract classes can have method bodies, that is, they can realize the specific functions of methods, but methods in interfaces can't.
- Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type.
- Interfaces cannot contain static code blocks and static methods (Methods decorated with static), while abstract classes can have static code blocks and static methods.
- A class can only inherit one abstract class, while a class can implement multiple interfaces.
2.6 interface declaration
The interface has the following characteristics:
- Interfaces are implicitly abstract. When declaring an interface, you do not need to use the abstract keyword.
- Each method in the interface is also implicitly abstract, and the abstract keyword is also not required when declaring.
- The methods in the interface are public.
<modifiers> interface <interface-name> { Constant-Declaration Method-Declaration Nested-Type-Declaration }
The interface declaration starts with a list of modifiers and may be empty.
Like classes, an interface can have a public or package level scope.
The keyword public is used to indicate that the interface has a public scope.
The missing scope modifier indicates that the interface has a package level scope. An interface with a package level scope can only be referenced within a member of its package.
The keyword interface is used to declare an interface, followed by the name of the interface.
The name of the interface must be a valid Java identifier.
The interface body follows its name and is enclosed in braces.
The body of the interface can be empty. The following is the simplest interface declaration:
interface CRUDdatable { // The interface body is empty }
Like classes, an interface has a simple name and a fully qualified name. The identifier after the keyword interface is its simple name.
The fully qualified name of an interface is formed by using its package name and a simple name separated by dots.
In the above example, CRUDdatable is a simple name, com java2s. Cruddable is a fully qualified name.
The rules for using simple and fully qualified names of interfaces are the same as those for classes.
The following code declares an interface called ReadOnly. It has a common scope.
package com.w3cschool; public interface ReadOnly { // The interface body is empty }
An interface declaration is always abstract, whether it is explicitly declared or not.
2.7 implementation interface
Interface specifies the protocol that the object must provide.
A class can provide a partial implementation of an abstract method of an interface, and in this case, the class must declare itself abstract.
The class that implements the interface uses the "implements" clause to specify the name of the interface.
The implementation clause consists of the keyword implements followed by a comma separated list of interface types.
A class can implement multiple interfaces.
When overriding the methods declared in the interface, you should pay attention to the following rules:
- When a class implements the method of an interface, it cannot throw a mandatory exception. It can only throw the mandatory exception in the interface or in the abstract class that inherits the interface.
- Class should maintain consistent method names when overriding methods, and should maintain the same or compatible return value types.
- If the class implementing the interface is an abstract class, there is no need to implement the methods of the interface.
When implementing the interface, you should also pay attention to some rules:
- A class can implement multiple interfaces at the same time.
- A class can only inherit one class, but can implement multiple interfaces.
- One interface can inherit another interface, which is similar to inheritance between classes
The general syntax of the class declaration that implements the interface is as follows:
...implements Interface name[, Other interface names, Other interface names..., ...] ...
Suppose you have a Circle class.
public class Circle implements Shape { void draw(){ System.out.println("draw circle"); } }
The class that implements the interface must be overridden to implement all abstract methods declared in the interface. Otherwise, the class must be declared abstract.
The default method of the interface is also inherited by the implementation class.
Implanted classes can choose not to override the default method.
Static methods in the interface are not inherited by the implementation class.
The following code defines two reference types, one from the Circle class and the other from the interface type.
Circle c = new Circle(); Shape shape = new Circle();
The variable c is of type Circle. It refers to the Circle object.
The second assignment is also valid because the Circle class implements the Shape interface, and each object of the Circle class is of Shape type.
2.7.1 interface implementation method
When a class fully implements an interface, it provides an implementation for all abstract methods of the implemented interface.
Method declarations in interfaces include constraints on methods. For example, the throws clause in a method declaration is a constraint on a method.
import java.io.IOException; interface Shape { void draw(double amount) throws IOException; } class Main implements Shape{ @Override public void draw(double amount) { // TODO Auto-generated method stub } }
Main's code is valid even if it discards the throws clause. When a class overrides an interface method, it is allowed to delete constraint exceptions.
If we use Shape type, we must deal with IOException.
import java.io.IOException; interface Shape { void draw(double amount) throws IOException; } class Main implements Shape{ @Override public void draw(double amount) { // TODO Auto-generated method stub } public void anotherMethod(){ Shape s = new Main(); try { s.draw(0); } catch (IOException e) { e.printStackTrace(); } draw(0); } }
2.7.2 realize multiple interfaces
A class can implement multiple interfaces. All interfaces implemented by the class are listed after the keyword implements in the class declaration.
By implementing multiple interfaces, the class agrees to provide implementations for all abstract methods in all interfaces.
interface Adder { int add(int n1, int n2); } interface Subtractor { int subtract(int n1, int n2); } class Main implements Adder, Subtractor { public int add(int n1, int n2) { return n1 + n2; } public int subtract(int n1, int n2) { return n1 - n2; } }
2.7.3 partially implemented interfaces
Class does not have to provide implementations for all methods.
If a class does not provide a full implementation of the interface, it must be declared abstract.
interface Calculator { int add(int n1, int n2); int subtract(int n1, int n2); } abstract class Main implements Calculator{ public int add(int n1, int n2) { return n1 + n2; } }
2.8 interface inheritance
One interface can inherit another interface, which is similar to the inheritance between classes. Interface inheritance uses the extends keyword, and the child interface inherits the methods of the parent interface.
An interface uses the keyword extends to inherit from other interfaces. The keyword extends is followed by a comma separated list of inherited interface names.
The inherited interface is called super interface, and the inherited interface is called sub interface.
Interface inherits the following members of its super interface:
- Abstract and default methods
- Constant field
- Nested Type
Interface does not inherit static methods from its super interface.
Interface can override the inherited abstract and default methods it inherits from its super interface.
If the super interface and sub interface have fields and nested types with the same name, the sub interface wins.
The following Sports interfaces are inherited by Hockey and Football interfaces:
// File name: sports java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } // File name: football java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } // File name: hockey java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); }
The Hockey interface declares four methods and inherits two methods from the Sports interface. Therefore, the class implementing the Hockey interface needs to implement six methods.
Similarly, a class that implements the Football interface needs to implement five methods, two of which come from the Sports interface.
2.8.1 implementation of inheritance conflict
The introduction of default methods allows classes to inherit conflicting implementations from their superclasses and superinterfaces.
Java uses three simple rules to resolve conflicts.
- Superclasses always win
- The most specific super interface wins
- Class must override conflicting methods
2.8.2 instanceof operator
We can use the instanceof operator to evaluate whether a reference type variable refers to an object of a specific class or its class implements a specific interface.
The general syntax of the instanceof operator is
referenceVariable instanceof ReferenceType
interface A { default String getValue(){ return "A"; } } interface B { default String getValue(){ return "B"; } } class MyClass implements B,A{ public String getValue(){ return "B"; } } public class Main { public static void main(String[] argv){ MyClass myClass = new MyClass(); System.out.println(myClass instanceof MyClass); System.out.println(myClass instanceof A); System.out.println(myClass instanceof B); } }
The above code produces the following results.
true
true
true
2.8.3 multi inheritance of interfaces
In Java, multi inheritance of classes is illegal, but interfaces allow multi inheritance.
In the multi inheritance of an interface, the extends keyword only needs to be used once, followed by the inherited interface. As follows:
public interface Hockey extends Sports, Event
The above program fragments are legally defined sub interfaces. Unlike classes, interfaces allow multiple inheritance, while Sports and events can define or inherit the same methods
2.9 marking interface
The most commonly used inheritance interfaces are those that do not contain any methods.
A tag interface is an interface without any methods and properties It simply indicates that its class belongs to a specific type for other code to test and allow to do something.
Function of tag interface: in a simple image, it is to mark (stamp) an object so that the object has some or some privileges.
For example: Java awt. The MouseListener interface in the event package inherits Java util. The EventListener interface is defined as follows:
package java.util; public interface EventListener {}
An interface without any method is called a tag interface. The tag interface is mainly used for the following two purposes:
Create a public parent interface:
Just like the EventListener interface, which is a Java API extended by dozens of other interfaces, you can use a tag interface to establish the parent interface of a set of interfaces. For example, when an interface inherits the EventListener interface, the Java virtual machine (JVM) knows that the interface will be used for the proxy scheme of an event.
To add a data type to a class:
This situation is the original purpose of the marked interface. The class implementing the marked interface does not need to define any interface methods (because the marked interface has no methods at all), but the class becomes an interface type through polymorphism.
3. Array (Arr [])
Array is one of the important data structures for every programming language. Of course, the implementation and processing of array are different in different languages.
Arrays provided in the Java language are used to store fixed size elements of the same type.
You can declare an array variable, such as numbers[100], instead of directly declaring 100 independent variables, number0, number1,..., number99.
3.1 declaring array variables
Array variables must be declared before arrays can be used in programs. The following is the syntax for declaring array variables:
dataType[] arrayRefVar; // Preferred method or dataType arrayRefVar[]; // The same effect, but not the preferred method
Note: it is recommended to use the declaration style of dataType[] arrayRefVar to declare array variables. dataType arrayRefVar [] style comes from C/C + + language and is adopted in Java to enable C/C + + programmers to quickly understand java language.
example
Here are code examples of these two Grammars:
double[] myList; // Preferred method or double myList[]; // The same effect, but not the preferred method
3.2 creating arrays
The Java language uses the new operator to create arrays. The syntax is as follows:
arrayRefVar = new dataType[arraySize];
The above syntax statement does two things:
1, An array is created using dataType[arraySize].
2, Assign the reference of the newly created array to the variable arrayRefVar.
The declaration of array variables and the creation of arrays can be completed in one statement, as follows:
dataType[] arrayRefVar = new dataType[arraySize]; //In addition, you can create arrays in the following ways. dataType[] arrayRefVar = {value0, value1, ..., valuek};
The elements of the array are accessed by index. The array index starts at 0, so the index value ranges from 0 to arrayrefvar length-1.
After the array opens up space, you can operate in the following ways:
The access of the array is completed through the index, that is: "array name [index]", but it should be noted that the index of the array starts from 0, so the index range is 0 ~ array length - 1. For example, for an array with three spaces, the available indexes are 0,1,2. If the access exceeds the index range of the array at this time, Java will be generated Lang. ArrayIndexOutOfBoundsException exception exception information;
When our array uses dynamic initialization to open up space, each element in the array is the default value of the corresponding data type of the array;
The array itself is an ordered set operation, so the content operation of the array is often completed in a circular mode. The array is a limited data set, so the for loop should be used.
In Java, there is a way to dynamically obtain the length of an array: array name length;
Example: define an int array
public class ArrayDemo { public static void main(String args[]) { int data[] = new int[3]; /*An array with a length of 3 is opened up*/ data[0] = 10; // First element data[1] = 20; // Second element data[2] = 30; // Third element for(int x = 0; x < data.length; x++) { System.out.println(data[x]); //Index control by loop } } }
In addition to declaring and opening up space, the array itself has another development mode.
Example: use step-by-step mode to open up array space
public class ArrayDemo { public static void main(String args[]) { int data[] = null; data = new int[3]; /*An array with a length of 3 is opened up*/ data[0] = 10; // First element data[1] = 20; // Second element data[2] = 30; // Third element for(int x = 0; x < data.length; x++) { System.out.println(data[x]); //Index control by loop } } }
However, remember that arrays are of reference data type, so you must open up space (instantiation) before using arrays. If arrays without open space are used, NullPointerException exception information will appear:
public class ArrayDemo { public static void main(String args[]) { int data[] = null; System.out.println(data[x]); } }
This principle is exactly the same as the object explained before.
Array will be used in development, but there are few operations like the above. In the actual development in the future, the concept of array will be used more and used directly. In most cases, it is just a for loop output.
3.3 processing arrays
The element type of array and the size of array are determined, so when dealing with array elements, we usually use basic loop or foreach loop.
Example
This example completely shows how to create, initialize and manipulate arrays:
public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Calculate the sum of all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Find maximum element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }
The compilation and operation results of the above examples are as follows:
1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5
3.4 foreach cycle
JDK 1.5 introduces a new type of loop, called foreach loop or enhanced loop, which can traverse arrays without subscripts.
The syntax format is as follows:
for(type element: array) { System.out.println(element); }
Example
This instance is used to display all elements in the array myList:
public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all array elements for (double element: myList) { System.out.println(element); } } }
The compilation and operation results of the above examples are as follows:
1.9 2.9 3.4 3.5
3.5 array as parameter of function
Arrays can be passed to methods as arguments. For example, the following example is a method to print elements in an int array.
public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }
The following example calls the printArray method to print out 3, 1, 2, 6, 4 and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
3.6 array as return value of function
public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; }
In the above example, the result array is used as the return value of the function.
3.7 Arrays
java. util. The arrays class can easily manipulate arrays, and all the methods it provides are static. It has the following functions:
Assign a value to the array: through the fill method.
Sort the array: sort in ascending order through the sort method.
Compare arrays: use the equals method to compare whether the element values in the array are equal.
Find array elements: binary search can be performed on the sorted array through the binarySearch method.
Please refer to the following table for details:
Serial number | Method and description |
---|---|
1 | public static int binarySearch(Object[] a, Object key) uses a binary search algorithm to search for objects (Byte,Int,double, etc.) with a given value in a given array. The array must be sorted before calling. If the lookup value is included in the array, the index of the search key is returned; Otherwise, it returns (- (insertion point) - 1). |
2 | public static boolean equals(long[] a, long[] a2) returns true if two specified long arrays are equal to each other. Two arrays are considered equal if they contain the same number of elements and all corresponding element pairs in the two arrays are equal. In other words, if two arrays contain the same elements in the same order, the two arrays are equal. The same method applies to all other basic data types (Byte, short, Int, etc.). |
3 | public static void fill(int[] a, int val) assigns the specified Int value to each element in the specified range of the specified Int array. The same method applies to all other basic data types (Byte, short, Int, etc.). |
4 | public static void sort(Object[] a) sorts the specified object array in ascending order according to the natural order of its elements. The same method applies to all other basic data types (Byte, short, Int, etc.). |
3.8 bubble sorting
public static void main(String[] args) { int[] a = {1,3,6,34,6,8,5,3,3}; int[] sort = sort(a); System.out.println(Arrays.toString(sort)); } //Bubble sorting //1. Compare two adjacent elements in the array. If the first number is larger than the second number, exchange their positions; //2. Each comparison produces a maximum or minimum number; //3. Less than one sorting in the next round; public static int[] sort(int[] array){ //Temporary variable int temp = 0; //Outer circle, judge how many times we have to go; for (int i = 0; i < array.length-1; i++) { boolean flag = false;//Reduce meaningless comparison by flag identification bit //The inner loop judges two numbers by price comparison. If the first number is larger than the second number, the position is exchanged for (int j = 0; j < array.length-1-i; j++) { if (array[j+1]>array[j]){ temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; flag = true; } } if (flag==false){ break; } } return array; }
3.9 sparse array
When most elements in an array (including multi-dimensional arrays) are 0 or an array with the same value, in order to save space and achieve the effect of compression, the data is represented by another structure, namely sparse array.
Processing method of sparse array: record how many rows and columns the array has and how many different values it has. The elements, rows, columns and values with different values are recorded in a small-scale array, so as to reduce the size of the program.
public static void main(String[] args) { //Create a 2D array int[][] array1 = new int[11][11]; array1[1][2] = 1; array1[2][3] = 2; //Output raw array for (int[] ints : array1) { for (int anInt : ints) { System.out.print(anInt+"\t"); } System.out.println(); } //Convert to sparse array save int sum = 0; for (int i = 0; i < 11 ; i++) { for (int j = 0; j < 11 ; j++) { if (array1[i][j]!=0) { sum++; } } } System.out.println(sum); //Create an array of sparse arrays int[][] array2 = new int[sum+1][3]; array2[0][0] = 11; array2[0][1] = 11; array2[0][2] = sum; //Traverse the two-dimensional array and store non-zero values in the sparse array. int count = 0; for (int i = 0; i < array1.length ; i++) { for (int j = 0; j < array1[i].length; j++) { if (array1[i][j]!=0){ count++; array2[count][0] = i; array2[count][1] = j; array2[count][2] = array1[i][j]; } } } //Output sparse array for (int i = 0; i < array2.length; i++) { System.out.println(array2[i][0]+ "\t"+array2[i][1]+"\t"+array2[i][2]+"\t"); } //Restore sparse array //1. Read sparse array int[][] array3 = new int[array2[0][0]][array2[0][1]]; //2. Restore its value to the element in it for (int i = 1; i < array2.length; i++) { array3[array2[i][0]][array2[i][1]] = array2[i][2]; } //3. Printing for (int[] ints : array3) { for (int anInt : ints) { System.out.print(anInt+"\t"); } System.out.println(); } }
3.10 two dimensional array
public static void main(String[] args) { int[][] array = {{1,2},{2,3},{3,4},{4,5}}; System.out.println(array[0][0]); System.out.println(array[0][1]); }
//The output result is
1
2
summary
May everyone adhere to the cause they love.
It's easy to give up, but it's hard to insist.
Refueling worker