Review of Java basics of Android (1)

Invalid Sign

1. Difference between object-oriented and process oriented @ h_ 404_ 7@ process oriented: process oriented performance is higher than object-oriented. Class calls require instantiation, which is expensive and consumes resources. Therefore, when performance is the most important consideration, such as MCU, embedded development, Linux / Unix, etc., process oriented development is generally adopted@ H_ 404_ 7@ object oriented: object oriented, easy to maintain, easy to reuse and easy to expand. Because object-oriented has the characteristics of encapsulation, inheritance and polymorphism, a low coupling system can be designed to make the system more flexible and easier to maintain. However, object-oriented performance is lower than process oriented performance@ H_ 404_ 7@2. What are the characteristics of Java language@ H_ 404_ 7@ (1) object oriented (encapsulation, inheritance, polymorphism); (2) Platform independence (Java virtual machine realizes platform independence); (3) Reliability and safety; (4) Support multithreading; (5) Support network programming... @ h_ 404_ 7@3. About JVM JDK and JRE @ h_ 404_ 7 @ bytecode (i.e. file with. Class extension) for virtual machines. By means of bytecode, Java language solves the problems of low execution efficiency and portability of traditional interpretative language to a certain extent. "Compile once and run at any time"

public class Main {
    public static void main(String[] args) {
        String a = new String("ab");//a为一个引用
        String b = new String("ab");//b为另一个引用,对象的内容相同
        String aa = "ab";//放入常量池中
        String bb = "ab";//从常量池中查找
        System.out.println("aa==bb?" + (aa == bb));//true
        System.out.println("a==b?"+(a==b));//false
        System.out.println("aEqb?"+a.equals(b));//true
        System.out.println("42==42.0"+(42 == 42.0));//true
    }
}

(* *) 19. Hashcode and equals (important) @ h_ 404_ 7 @ the interviewer may ask you, "have you rewritten hashcode and equals, and why do you have to rewrite the hashcode method when rewriting equals?" @ h_ 404_ 7 @ hashcode() introduction @ h_ 404_ 7@ hashcode() is used to obtain hash code, also known as hash code; It actually returns an int integer. This hash code is used to determine the index position of the object in the hash table. Hashcode () is defined in object. Java of the JDK, which means that any class in java contains the hashcode () function@ H_ 404_ 7@ hash table stores key value pairs. Its feature is that it can quickly retrieve the corresponding "value" according to the "key". This makes use of hash code! (you can quickly find the object you need) @ h_ 404_ 7 @ Why hashcode@ H_ 404_ 7@ let's take "how HashSet checks for duplicates" as an example to explain why hashcode is needed: when you add an object to a HashSet, HashSet will first calculate the hashcode value of the object to determine the location of the object, and will also compare it with the hashcode value of other added objects. If there is no matching hashcode, HashSet will assume that the object does not appear repeatedly. However, if an object with the same hashcode value is found, the equals () method will be called to check whether the objects with the same hashcode are really the same. If the two are the same, HashSet will not make its join operation successful. If it is different, it will be hashed to another location. (from my java enlightenment book head first Java, Second Edition). In this way, we greatly reduce the number of equals and greatly improve the execution speed. The methods to solve the conflict include open addressing method (linear detection re hashing, secondary detection re hashing, pseudo-random detection re hashing), re hashing method and chain address method@ H_ 404_ 7@ from the above, we can see that the function of hashcode () is to obtain hash code, also known as hash code; It actually returns an int integer. This hash code is used to determine the index position of the object in the hash table** Hashcode () is useful only in hash tables, but not in other cases** In the hash table, hashcode () is used to obtain the hash code of the object and then determine the position of the object in the hash table@ H_ 404_ 7@hashCode () regulations related to equals () @ h_ 404_ 7 @ 1. If two objects are equal, hashcode must be the same @ H_ 404_ 7 @ 2. If the two objects are equal, calling the equals method on the two objects will return true@H_ 404_ 7 @ 3. Two objects have the same hashcode value, and they are not necessarily equal @ H_ 404_ 7 @ 4. Therefore, if the equals method is overridden, the hashcode method must also be overridden @ H_ 404_ 7 @ 5. The default behavior of hashcode() is to generate unique values for objects on the heap. If hashcode () is not overridden, the two objects of the class will not be equal in any case (even if the two objects point to the same data) @ h_ 404_ 7@20. Why is there only value passing in Java@ H_ 404_ 7@ call by value means that the method receives the value provided by the caller and is called by reference (call by reference) indicates that the method receives the variable address provided by the caller. A method can modify the variable value corresponding to the passed reference, but cannot modify the variable value corresponding to the passed value call. @ h_404_7 @ the Java programming language does not use the reference call on the object. In fact, the object reference is passed by value. @ h_404_7 @ the following is a summary in Java Usage of method parameters: @ h_404_7 @ 1. A method cannot modify parameters of a basic data type (i.e. numeric or Boolean). @ h_404_7 @ 2. A method can change the state of an object parameter. @ h_404_7 @ 3. A method cannot let an object parameter reference a new object.

  public static void main(String[] args) {
        //Java程序设计语言总是采用按值调用。也就是说,方法得到的是所有参数值的一个拷贝,
        // 也就是说,方法不能修改传递给它的任何参数变量的内容。
        int num1 = 10;
        int num2 = 20;
        swap(num1, num2);
        System.out.println("Main方法中 num1:" + num1);
        System.out.println("Main方法中 num2:" + num2);
//        通过 example2 我们已经看到,实现一个改变对象参数状态的方法并不是一件难事。
//        理由很简单,方法得到的是对象引用的拷贝,对象引用及其他的拷贝同时引用同一个对象。
        int[] arra = {1, 2, 3, 4, 5};
        System.out.println(arra[0]);
        change(arra);
        System.out.println(arra[0]);
        Student s1 = new Student("小张");
        Student s2 = new Student("小李");
        swap01(s1,s2);
        System.out.println("Main s1"+s1.getName());
        System.out.println("Main s2"+s2.getName());
    }
    private static void swap01(Student s1, Student s2) {
        Student temp = s1;
        s1 = s2;
        s2= temp;
        System.out.println("swap s1"+s1.getName());
        System.out.println("swap s2"+s2.getName());
    }
    private static void change(int[] arra) {
        arra[0] = 0;
    }
    private static void swap(int num1, int num2) {
        int tmp = num1;
        num1 = num2;
        num2 = tmp;
        System.out.println("Swap方法中 num1:" + num1);
        System.out.println("Swap方法中 num2:" + num2);
}}

        //方法1:通过 Scanner
        Scanner input =  new Scanner(system.in);
        String s = input.nextLine();

        //方法2:通过BufferedReader
        BufferedReader input_01 = new BufferedReader(new InputStreamReader(system.in));
        String s1 = input_01.readLine();
        input.close();
        input_01.close();

27. How many types of IO streams are there in Java? What's the difference between bio, NiO and AIO@ H_ 404_ 7@ InputStream / reader: the base class of all input streams. The former is byte input stream and the latter is character input stream@ H_ 404_ 7 @ OutputStream / writer: the base class of all output streams. The former is byte output stream and the latter is character output stream@ H_ 404_ 7@27.1.Java How many IO streams are there in the@ H_ 404_ 7@ according to the flow direction, it can be divided into input flow and output flow@ H_ 404_ 7@ according to the division of operation units, it can be divided into byte stream and character stream@ H_ 404_ 7@ according to the role of flow, it is divided into node flow and processing flow@ H_ 404_ 7@27.2.BIO What's the difference between NiO and AIO@ H_ 404_ 7@ bio (blocking I / O): synchronous blocking I / O mode. Data reading and writing must be blocked in a thread and wait for it to complete. Thread pool itself is a natural funnel, which can buffer some connections or requests that the system can't handle@ H_ 404_ 7@ NiO (new I / O): NiO is a synchronous non blocking I / O model that provides abstractions such as channel, selector, buffer, etc. It supports buffer oriented, channel based I / O operations. For low load and low concurrency applications, synchronous blocking I / O can be used to improve development speed and better maintainability; For high load and high concurrency (Network) applications, NiO's non blocking mode should be used for development@ H_ 404_ 7@ AIO: asynchronous non blocking IO model. Asynchronous IO is implemented based on event and callback mechanism, that is, it will return directly after application operation and will not be blocked there. When the background processing is completed, the operating system will notify the corresponding thread for subsequent operation@ H_ 404_ 7@28. Summary of common keywords: static, final, this, super@H_ 404_ 7@final Keywords: mainly used in three places: variables (basic data type: initialization cannot be modified, reference type: cannot change the direction), methods (inherited subclasses cannot modify the meaning; improve efficiency), and classes (classes cannot be inherited; the method in the class defaults to final)@ H_ 404_ 7@this Keyword: this keyword is used to reference the current instance of the class. It is optional to make the code easy to read and understand@ H_ 404_ 7@super Keyword: Super keyword is used to access variables and methods of the parent class from a subclass@ H_ 404_ 7@ both must be on the first line and cannot appear in the static method@ H_ 404_ 7@static Keywords are mainly used in the following four scenarios: @ h_ 404_ 7 @ exists in the method area stored in the JAVA memory area@ H_ 404_ 7@ 1. Modify member variables and member methods: members modified by static belong to a class, not an object of a single class, which are shared by all objects in the class, and can be called through the class name. The member variables declared by static belong to static member variables, which are stored in the method area of JAVA memory area. Calling format: class name. Static variable name. Class name. Static method name () @ h_ 404_ 7 @ 2. Static code block: the static code block is defined outside the method in the class, and the static code block is executed before the non static code block (static code block - > non static code block - > construction method). No matter how many objects are created by this class, the static code block is executed only once. @ h_ 404_ 7 @ 3. Static inner class (static can only modify inner class if it modifies class): there is one biggest difference between static inner class and non static inner class: after compilation, the non static inner class will implicitly save a reference, which refers to the peripheral class that created it, but the static inner class does not. Without this reference, it means: 1. Its creation does not depend on the creation of peripheral classes. 2. 2. It cannot use non static member variables and methods of any peripheral class@ H_ 404_ 7 @ 4. Static import package (used to import static resources in a class, new features after 1.5): the format is: import static. The combination of these two keywords can specify to import the specified static resources in a class, and it is not necessary to use the class name to call the static members in the class. You can directly use the static member variables and member methods in the class@ H_ 404_ 7@29.Collections Common methods of tool class and arrays tool class @ h_ 404_ 7 @ 1. Common methods of collections tool class: @ h_ 404_ 7@ (1) sorting; (2) Find and replace operations; (3) Synchronization control (not recommended) @ h_404_7@ (1) sort:

void reverse(List list)//反转
void shuffle(List list)//随机排序
void sort(List list)//按自然排序的升序排序
void sort(List list, Comparator c)//定制排序,由Comparator控制排序逻辑
void swap(List list, int i , int j)//交换两个索引位置的元素
void rotate(List list, int distance)//旋转。当distance为正数时,将list后distance个元素整体移到前面。当distance为负数时,将 list的前distance个元素整体移到后面。

int binarySearch(List list, Object key)//对List进行二分查找,返回索引,注意List必须是有序的
int max(Collection coll)//根据元素的自然顺序,返回最大的元素。 类比int min(Collection coll)
int max(Collection coll, Comparator c)//根据定制排序,返回最大元素,排序规则由Comparatator类控制。类比int min(Collection coll, Comparator c)
void fill(List list, Object obj)//用指定的元素代替指定list中的所有元素。
int frequency(Collection c, Object o)//统计元素出现次数
int indexOfSubList(List list, List target)//统计target在list中第一次出现的索引,找不到则返回-1,类比int lastIndexOfSubList(List source, list target).
boolean replaceAll(List list, Object oldVal, Object newVal), 用新元素替换旧元素

2. Common operations of arrays class: sort(); Search: binarysearch(); Compare: equals(); Fill: fill(); Transfer list: aslist(); To string: tostring(); Copy: copyof() @ h_ 404_ 7 @ 2.1.arrays.sort can quickly sort the array and arrange the specified range of the array in ascending order. Parallelsort sorts the specified array in numerical order (parallel). You can sort strings

private static void copyof() {
        // *************复制 copy****************
        // copyOf 方法实现数组复制,h为数组,6为复制的长度
        int[] h = { 1, 2, 3, 3, 3, 3, 6, 6, 6, };
        int i[] = Arrays.copyOf(h, 6);
        System.out.println("Arrays.copyOf(h, 6);:");
        // 输出结果:123333
        for (int j : i) {
            System.out.print(j);
        }
        // 换行
        System.out.println();
        // copyOfRange将指定数组的指定范围复制到新数组中
        int j[] = Arrays.copyOfRange(h, 6, 11);
        System.out.println("Arrays.copyOfRange(h, 6, 11):");
        // 输出结果66600(h数组只有9个元素这里是从索引6到索引11复制所以不足的就为0)
        for (int j2 : j) {
            System.out.print(j2);
        }
        // 换行
        System.out.println();
}

    String []Array = new String[]{"Apple","Orange","Banana"};
    List<String> myList = Arrays.asList(Array);
    //上面和下面两者等价。
     List<String> mylist_01 = Arrays.asList("Apple","Orange","Banana");
注意:

Note: @ h_ 404_ 7@ 1. After arrays. Aslist() converts an array into a collection, the underlying layer is actually an array. Using the modification methods of the collection: add(), remove (object), clear() will throw exceptions. Wrapping type arrays can solve this problem by converting ints to integers.

  Int[] myArray = { 1, 2, 3 };
  List myList = Arrays.asList(myArray);
  System.out.println(myList.size());//1
  System.out.println(myList.get(0));//数组地址值
  System.out.println(myList.get(1));//报错:Arrayindexoutofboundsexception

2. The array passed must be an object array, not a basic type array@ H_ 404_ 7@29.2. How to correctly convert an array to ArrayList@ H_ 404_ 7@ the easiest way (recommended)

        List<String> result = new ArrayList<>(Arrays.asList("apple","banana","orange"));
        //方法一:超级for循环遍历
        for(String t1:result){
            System.out.println(t1);
        }
        //方法二:对于ArrayList来说速度比较快, 用for循环, 以size为条件遍历:
        for(int i = 0;i<result.size();i++){
            System.out.println(result.get(i));
        }
        //方法三:集合类的通用遍历方式, 从很早的版本就有, 用迭代器迭代
        Iterator it =result.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }

Invalid Sign

String [] s= new String[]{
    "dog", "lazy", "a", "over", "jumps", "fox", "brown", "quick", "A"
};
List<String> list = Arrays.asList(s);
Collections.reverse(list);
s=list.toArray(new String[0]);//没有指定类型的话会报错

Invalid Sign

Invalid Sign

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>