Array features in java

Source: Internet
Author: User

An array is a data type that is generally used in all languages. It represents a set of data of the same type and has a fixed length and occupies continuous space in the memory. In C, C ++, and other languages, the definition of arrays is concise and clear, while java does have some confusing features. This article attempts to analyze these features. Is the array in Java an object? Java and C ++ are both object-oriented languages. When using these languages, we can directly use standard class libraries, or use combination and inheritance and other object-oriented features to build our own classes, and create Objects Based on the classes we build. So should we consider the following question: is an array an object in an object-oriented language? To determine whether an array is an object, first define the object, that is, the definition of the object. At a higher level, an object is an instance created based on a class, indicating a specific individual in a certain thing. Objects have various attributes and specific behaviors. At a lower level, from the computer perspective, the object is a memory block in the memory, which encapsulates some data, that is, the attributes defined in the class. Therefore, objects are used to encapsulate data. Note: 1) a small red rectangle represents a reference (Address) or a basic type of data, and a large red rectangle represents an object, multiple small red rectangles are combined to form an object. 2) name indicates only one reference in the object, that is, an address value. It points to a real String object. References and objects are strictly distinguished here. In Java, does the array meet the preceding conditions? At a higher level, arrays are not a specific individual in a certain type of things, but a collection of multiple individual. Then it should not be an object. From a computer perspective, arrays are also a memory block and some data is encapsulated. This can also be called an object. The following is an array representation in the memory: In this case, the array can be either an object or an object. Whether or not arrays are used as objects depends on the Java designer. Whether the array is an object or not. Code verification: [java] int [] a = new int [4]; //. length; // the reference to the attribute cannot be considered as the statement int len =. length; // save a field in the array to indicate the length of the array. // The following method indicates that an array can be called. An array in java is an object. these methods are the methods in the Object, so it is certain that the top-level parent class of the array is also Object. clone ();. toString (); on Array a, you can access its attributes or call some methods. It can be basically determined that the array in java is also an object, which has some basic features of other objects in java: it encapsulates some data, can access attributes, and can call methods. Therefore, arrays are objects. In C ++, although the array encapsulates data, the array name is just a pointer pointing to the first element in the array. There is neither an attribute nor a method to call it. The following code shows: [cpp] int main () {int a [] = {1, 2, 3, 4}; int * pa = a; // The attribute cannot be accessed, you cannot call a method. Return 0;} therefore, arrays in C ++ are not objects but a collection of data and cannot be used as objects. Java is a strongly typed language. Since it is an object, it must belong to a type. For example, to create an object based on the Person class, the object type is Person. So what is the array type? See the following code: [java] int [] a1 = {1, 2, 3, 4}; System. out. println (a1.getClass (). getName (); // The printed array class name is [I String [] s = new String [2]; System. out. println (s. getClass (). getName (); // The printed array class name is [Ljava. lang. string; String [] [] ss = new String [2] [3]; System. out. println (ss. getClass (). getName (); // The printed array class name is [[Ljava. lang. string; print out That the a1 type is [I, the s type is [Ljava. lang. string;, the ss type is [[Ljava. lang. string; therefore, arrays are also of type. This type is strange. You can say that the a1 type is int [], which is understandable. However, we did not create this class by ourselves, nor did we find this class in the Java standard library. That is to say, neither our own code nor JDK has the following definition: [java] public class int [] {//... //... //...} this can only be explained by the fact that an array type is automatically created by the virtual machine. The array type can be the same as the eight basic data types as the built-in java type. This type of naming rule is as follows: * Each dimension is represented by a [; the first two [, which indicates a two-dimensional array. * [The following is the element type in the array (including the basic data type and reference data type). At the java language level, s is an array and an object, so its type should be String [], which is reasonable. However, in JVM, its type is [java. lang. String. By the way, the common class type in JVM is package name + class name, that is, full qualified name. The representation of the same type in java and in virtual machines may be different. The inheritance relationship of arrays in Java has been verified above. arrays are objects, that is, Arrays can be operated as objects. In addition, the array has a special type in the virtual machine. Since it is an Object, follow the rules in the Java language-Object is God, that is to say, the top-level parent class of all classes is Object. The top-level parent class of the array must also be an Object, which means that the array Object can be directly transformed to the Object, or forced type conversion down, or the instanceof keyword can be used for type determination. All these are the same as common objects. The code below is as follows: [java] // 1 has been tested in test1 () and the following conclusion is obtained: The array is also an Object, and the top-level parent class of the array is an Object, therefore, you can convert int [] a = new int [8] to an upward direction. Object obj = a; // The parent class of the array is also an Object, can I transform a to Object/2, so can I perform a downward transformation? Int [] B = (int []) obj; // you can perform a downward transformation. // 3. Can you use the instanceof keyword to determine whether to use the instanceof keyword? If (obj instanceof int []) {// you can use the instanceof keyword to determine the type of System. out. println ("the actual type of obj is int []");} another "inheritance" relation of arrays in Java is correct in the following code, but it is easy for us to wonder: [java] String [] s = new String [5]; Object [] obja = s; // set up, the Object [] type reference of String [] can be used to receive an array Object of the String [] type? The above verification shows that the top-level parent class of the array type must be an Object. Who is the direct parent class of s in the above Code? It is hard to say that String [] inherits from Object [], while Object [] inherits from Object again? Let's verify this problem through reflection: [java] // 5 so the direct parent class of String [] is Object [] or Object? System. out. println (s. getClass (). getSuperclass (). getName (); // print the result as java. lang. object: the direct parent class of String [] is Object rather than Object []. The Code shows that the direct parent class of String [] is Object rather than Object []. However, the reference of Object [] can clearly point to an Object of the String [] type. So their inheritance relationship is a bit like this: This violates the Java single inheritance principle. String [] cannot inherit objects, but also Object []. The class diagram above must be incorrect. It can only be explained as follows: the array class directly inherits the Object. References to Object [] types can point to objects of the String [] type. This situation can only be a special case in Java syntax, it is not strictly inherited. That is to say, String [] does not inherit from Object [], but I can allow you to transform to Object []. This feature is a special privilege for you. In fact, this relationship can be expressed as follows: if there are two classes A and B, if B inherits (extends), then A [] type references can point to B [] type objects. The following code is used: [java] public static class Father {} public static class Son extends Father {} [java] // 6? Father is Son's direct parent class Son [] sons = new Son [3]; Father [] fa = sons; // set up // 7. Is the direct parent class of Son [] Father [], Object [], or Object? System. out. println (sons. getClass (). getSuperclass (). getName (); // print the result as java. lang. the parent class of Son [] is the Object. The conclusions above can be extended to two-dimensional arrays and multi-dimensional arrays: [java] Son [] [] sonss = new Son [2] [4]; Father [] [] fathers = sonss; The above code can be understood as follows: think of the Father [] [] array as a one-dimensional array, the element in the array is Father [], and the Son [] [] array as a one-dimensional array, the element in the array is Son [], because the reference of the Father [] type can point to the Son [] type object. Therefore, according to the above conclusion, the reference of Father [] [] can point to Son [] [] type objects. Array usage does not apply to basic data types: [java] int [] aa = new int [4]; // Object [] objaa = aa; // incorrect, it cannot be compiled. Because int Is not the reference type and the Object is not the parent class of int, automatic packing does not work here. However, this method is acceptable: [java] Object [] objss = {"aaa", 1, 2.5}; in this case, automatic packing can work, that is, the Object array can store any value, including the basic data type. Why does Java provide such a syntax feature for arrays? That is to say, what is the role of this syntax? Those who have compiled the Sqlite database operating program in Android may have discovered this phenomenon. They use an Object [] to reference and receive all array objects. When compiling SQL statements, provide the corresponding values for placeholders in SQL statements. [Java] db.exe cSQL ("insert into person VALUES (NULL ,?, ?) ", New Object [] {person. name, person. age}); therefore, this feature is mainly used for passing parameters in methods. If you do not pass an array, but pass each value in sequence, the method parameter list will become lengthy. If a specific array type is used, such as String [], the type is limited and the flexibility is lost. Therefore, it is better to pass the array type. However, if there is no such array feature (if there are two classes A and B, if B inherits (extends), then A [] type reference can point to B [] type Object), then the array type can only be received through the Object type, in this way, each element in the array cannot be accessed or traversed within the method. The following code: [java] private static void test3 () {String [] a = new String [3]; doArray (a);} private static void doArray (Object [] objs) {} private static void doArray1 (Object obj) {// arrays cannot be received by objects, as a result, you cannot access the elements of the array // obj [1] // error // if you want to convert obj to an array within the method, risk of type conversion exception/Object [] objs = (Object []) obj;} private static void doArray2 (String [] strs) {// If an array of a specific type is applied, the type is limited, and flexibility and versatility are lost.} private static void doArray3 (String Name, int age, String id, float account) {// If an array is not applicable, passing parameters in turn will make the parameter list lengthy and hard to read} so far, the array features are summarized. The bold section above is an important conclusion. The entire source code is provided below: Source Code [java] package com. pansoft. zhangjg. testarray; public class ArrayTest {/*** @ param args */public static void main (String [] args) {test1 (); test2 (); test3 ();} /*** array has this feature: * if there are two classes A and B, if B inherits (extends), then A [] type reference can point to B [] type object * special features of the test array convenience of parameter transfer */private static void test3 () {String [] a = new String [3]; doArray (a);} private static void doArray (Object [] objs) {} private static v Oid doArray1 (Object obj) {// arrays cannot be received by objects, as a result, you cannot access the elements of the array // obj [1] // error // if you want to convert obj to an array within the method, risk of type conversion exception/Object [] objs = (Object []) obj;} private static void doArray2 (String [] strs) {// If an array of a specific type is applied, the type is limited, and flexibility and versatility are lost.} private static void doArray3 (String name, int age, String id, float account) {// If an array is not applicable, passing parameters in turn will make the parameter list lengthy and difficult to read}/*** test the integration relationship of the array, whether the inheritance relationship is related to the element type in the array */private static void test 2 () {// 1 has been tested in test1 () and the following conclusions are obtained: The array is also an Object, and the top-level parent class of the array is an Object, therefore, you can convert int [] a = new int [8] to an upward direction. Object obj = a; // The parent class of the array is also an Object, can I transform a to Object/2, so can I perform a downward transformation? Int [] B = (int []) obj; // you can perform a downward transformation. // 3. Can you use the instanceof keyword to determine whether to use the instanceof keyword? If (obj instanceof int []) {// you can use the instanceof keyword to determine the type of System. out. println ("the actual type of obj is int []");} // is the code below 4 true? String [] s = new String [5]; Object [] obja = s; // true, the Object [] can be referenced to receive the Object of String [] // 5. Is the direct parent class of String [] an Object [] or an Object? System. out. println (s. getClass (). getSuperclass (). getName (); // print the result as java. lang. object. Does it mean that the direct parent class of String [] is Object instead of Object [] // 6? Father is Son's direct parent class Son [] sons = new Son [3]; Father [] fa = sons; // set up // 7. Is the direct parent class of Son [] Father [], Object [], or Object? System. out. println (sons. getClass (). getSuperclass (). getName (); // print the result as java. lang. object indicates that the direct parent class of Son [] is Object/***. If A is the parent class of B, then A [] type reference can point to B [] Type Variable *, but the direct parent class of B [] is Object, the parent classes of all arrays are objects * // 8. The above conclusions can be extended to two-dimensional arrays Son [] [] sonss = new Son [2] [4]; father [] [] fathers = sonss; // treats the Father [] [] array as a one-dimensional array, the element in the array is Father [] // The Son [] [] array is regarded as a one-dimensional array, the element in the array is Son [] // because the reference of Father [] type can point to Son [] type object //, according to the above conclusion, Fa The reference of ther [] [] can point to Son [] [] type object/*** extension conclusion: * because the Object is a parent class of all reference types *, the Object [] reference can point to any Object that references an array of data types. for example, * Object [] objs = new String [1]; * Object [] objs = new Son [1]; ** // 9 is the code below true? Int [] aa = new int [4]; // Object [] objaa = aa; // The Error Code cannot be compiled. // This is incorrect, because the Object is not the parent class of the int type, automatic packing does not work here // 10 is OK? Object [] objss = {"aaa", 1, 2.5}; // true}/*** test whether an array is an Object in java * if it is an Object, so what is his type? */Private static void test1 () {int [] a = new int [4]; //. length; // the reference to the attribute cannot be considered as the statement int len =. length; // save a field in the array to indicate the length of the array. // The following method indicates that an array can be called. An array in java is an object. these methods are the methods in the Object, so it is certain that the top-level parent class of the array is also Object. clone ();. toString ();/*** java is a strongly typed language. An object always has a specific type, such as Person p = new Person (); * The object p (reference) is of the Person class. This Person class is compiled by ourselves * So what is the array type? The following uses the Reflection Method for verification */int [] a1 = {1, 2, 3, 4}; System. out. println (a1.getClass (). getName (); // The printed array class name is [I String [] s = new String [2]; System. out. println (s. getClass (). getName (); // The printed array class name is [Ljava. lang. string; String [] [] ss = new String [2] [3]; System. out. println (ss. getClass (). getName (); // The printed array class name is [[Ljava. lang. string;/***. Therefore, arrays also have types, but this type is not a class defined by a programmer or * in jdk, instead, the naming rule for the class * type specifically created by the virtual machine at runtime is: * Each dimension is represented by; * [the following is the element type in the array (including the basic data type and reference data type) ** at the java language level, s is an array and an object, its type should be String [], * but in JVM, its type is [java. lang. string ** by the way, the common class type in JVM is package name + class name, that is, the fully qualified name */} public static class Father {} public static class Son extends Father {}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.