Harvesting in the Java learning process

Source: Internet
Author: User

1. String <--> Date
这种转换要用到java.text.SimpleDateFormat类    字符串转换成日期类型:  方法1:    也是最简单的方法 Date date=new Date("2008-04-14");    方法2:    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");//小写的mm表示的是分钟  String dstr="2008-4-24";  java.util.Date date=sdf.parse(dstr);        日期转换成字符串:    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  java.util.Date date=new java.util.Date();  String str=sdf.format(date);  
2. Iterable & Iterator
Iterator是迭代器类 Iterable是接口,实现了Iterable就可以调用Iterator的方法  进而使用next hasNext方法  当然也可以直接impemnts Iterator那么Iterable存在的必要?Iterator接口的核心方法是next() hasNext() 是依赖于迭代器当前的迭代位置的如果Collection直接实现Iterator接口势必导致集合对象包含当前迭代位置的数据(指针) 党籍和在不同方法之间传递时,由于当前迭代位置不可预知,那么next方法的结果变成不可预知除非再为Iterator接口添加一个reset方法,用来重置当前迭代位置,但即使这样COllection也只能同时存在一个当前迭代位置而Iterable则不然,每次调用都会返回一个从头开始计数的迭代器多个迭代器是互不干扰的
3. String.contains Source Code
String.contains (charsequence) 1. Abstract.contains (a) 2. IndexOf (a.tostring) >-13. IndexOf (A, 0) 4. indexof (value, 0, value.length, str.value, 0, Str.value.length, FromIndex) 5. Value is a character array that is an internal implementation of string 6. /* * Source Bstract * Sourceoffset 0 * Sourcecount 7 * TARGETAC * Targetoffset 0 * Targetcount 2 * f Romindex 0 * * */public int indexOf (char[] source, int sourceoffset, int sourcecount,char[] target, int targetoffset, I NT Targetcount,int FromIndex) {if (FromIndex >= sourcecount) {return (Targetcount = = 0? sourcecount:-1);} if (FromIndex < 0) {FromIndex = 0;} if (Targetcount = = 0) {return fromIndex;}     Char first = Target[targetoffset];                        Let's say Bstract find AC. You find the last letter to find a what's the use of it? So at least you have to find a in the bottom second, or you can't find int max = Sourceoffset + (sourcecount-targetcount); The first if failure or the second if failure will trigger I>max and then return 1 and the first match but the other mismatch for (int i = Sourceoffset + FromIndex; I <= Max; i++) {/* look for first character. */if (Source[i]! = first) {WHIle (++i <= max && source[i]! = first);} /* Found first character, now looking at the rest of the V2 */if (i <= max) {//Determine if you want to see the character int j = i + 1;int end = j + targetc        ount-1;for (int k = Targetoffset + 1; J < end && source[j]== Target[k]; j + +, k++); Only the first character to compare whether the other is found by comparing J to end can if (j = = end) {/* Found whole string. */return i-sourceoffset;}} return-1;}
4. Final

What are the characteristics of final modified classes?

Java关键字final有“这是无法改变的”或者“终态的”含义,它可以修饰非抽象类、非抽象类成员方法和变量。?final类不能被继承,没有子类,final类中的方法默认是final的。 ?final方法不能被子类的方法覆盖,但可以被继承。 ?final成员变量表示常量,只能被赋值一次,赋值后值不再改变。 ?final不能用于修饰构造方法。 注意:父类的private成员方法是不能被子类方法覆盖的,因此private类型的方法默认是final类型的。

Final class

The final class cannot be inherited, so the member methods of the final class have no chance of being overwritten, and the default is final. In the design class, if the class does not need to have subclasses, the implementation details of the class are not allowed to change, and it is certain that the class will not be extended, then it is designed as the final class.

Final method

If a class does not allow its subclasses to overwrite a method, you can declare this method as the final method. There are two reasons for using the final method:

① locks the method to prevent any inherited classes from modifying its meaning and implementation.

② is efficient, the compiler will go into the embedding mechanism when it encounters the final method, greatly improving the efficiency of execution.

For example:

public class Test1 { public static void main(String[] args) { // TODO 自动生成方法存根 } public void f1() { System.out.println("f1"); } //无法被子类覆盖的方法 public final void f2() { System.out.println("f2"); } public void f3() { System.out.println("f3"); } private void f4() { System.out.println("f4"); } } public class Test2 extends Test1 { public void f1(){ System.out.println("Test1父类方法f1被覆盖!"); } public static void main(String[] args) { Test2 t=new Test2(); t.f1(); t.f2(); //调用从父类继承过来的final方法 t.f3(); //调用从父类继承过来的方法 //t.f4(); //调用失败,无法从父类继承获得 } }

Final variable (constant)

A constant is represented by a final modified member variable, which cannot be changed once the value is given.

There are three final modified variables: Static variables, instance variables, and local variables, representing three types of constants, respectively.

As you can see from the example below, once the initial value is given to the final variable, it cannot be changed.

Package org.leizhimin; public class Test3 {private final String s= "final instance variable S"; private final int a=100; public final int b=90; public static fi nal int c=80; private static final int d=70; public final int E; Final blank, the initial value must be initialized when initializing the object public Test3 (int x) {e=x;}/** * @param args */public static void main (string[] args) {Test3 T =new Test3 (2); t.a=101; Error, the value of the final variable cannot be changed once the//t.b=91 is given; Error, the value of the final variable cannot be changed once the//t.c=81 is given; Error, the value of the final variable cannot be changed once the//t.d=71 is given; Error, the value of the final variable cannot be changed System.out.println (T.A) once it is given; System.out.println (T.B); System.out.println (T.C); accessing static fields System.out.println (T.D) with object mode is not recommended; accessing static fields System.out.println (TEST3.C) with object mode is not recommended; System.out.println (TEST3.D); System.out.println (TEST3.E); Error because E is final and differs depending on the value of the object. System.out.println (T.E); Test3 t1=new Test3 (3); System.out.println (t1. E); The final blank variable e differs from the object by its private void test () {System.out.println (new Test3 (1)). A); System.out.println (TEST3.C); System.out.println (TEST3.D); } public void Test2 () {final int A;//final blank, if requiredWhen the final int b=4 is assigned; The case of local constants--final for local variables final int c; Final blank, has not been assigned. A=3; a=4; Error, the value has been assigned. b=2; Error, the value has been assigned. } }

In addition, when the final variable is defined, it can be declared without giving the initial value, and this variable is also called the final blank, no matter what

case, the compiler ensures that the blank final must be initialized before it can be used. However, final blanks in final keyword final

Provides greater flexibility in the use of the final data members in a class can be implemented according to the object,

There are characteristics that keep them constant.
Final parameter

When the function parameter is the final type, you can read it using the parameter, but you cannot change the value of the parameter.

public class Test4 { public static void main(String[] args) { new Test4().f1(2); } public void f1(final int i){ //i++; //i是final类型的,值不允许改变的. System.out.print(i); }
5. | & | |
|:逻辑或 不管怎样都会执行左右两边||: 断言已经能判断真假  就不需要往后继续判断或 strId == null || strId.trim().equals("")
6. Java.util.Date & MySQL 0000-00-00 0:00:00
java.util.Date d = rs.getTImestamp("");
7. Program Optimization
<1>常用逻辑抽象为方法<2>常用变量声明为final  可以用接口或者枚举实现<3>内部类  匿名类   外部类<4>多态<5>良好的注释<6>异常的处理  资源的关闭<7>对象的声明与销毁<8>问题的解决方案  线程  异步<9>进阶  设计模式 动态代理<10>不要再一个类里处理另一个类的逻辑   应该在另一个类封装<11>几个类有相同的逻辑  定义抽象类  继承<12>   类内  static   不用每次用的时候都load进内存  <13>根据用户的需求 改变代码 --->配置文件
8. Reference Assignment Issues
可以让别人传过来  也可以自己过去接受
9.Java a call relationship between a neutron class and the construction method of a parent class
  在 Java 中,无论是 explicit 还是 implicit 方式,都要求在子类的构造方法中调用其父类的构造方法。如果父类无构造方法(其实是一个默认无参的构造方法),那么子类的构造方法中会自动进行调用;如果 父类有自己的构造方法(这时父类不会有默认无参的构造方法),那么在子类的构造方法中,必须要调用父类的某个构造方法,而且必须是在构造方法的第一个语句 中进行调用。究其原因,想必是 Java 语言设计者,要求子类有责任保证它所继承的父类尽快进入到一个稳定、完整的状态中。试想,如果没有这个约束,那么子类的某个继承自父类的方法可能会使用到父类中的一些变量,而这些变量并没有进行初始化,从而产生一些难以预料的后果,因此构造子类的对象前,必须构造父类的对象,并将之隐含于子类对象之中,使用关键字super引用父类对象。也因此,当一个类的构造方法是 private 时,它是不可被 extends 的,因为子类构造方法难以调用到这个父类的构造方法。
Ten Java Stacks
    • Policies for memory allocation

      According to the compiling principle, there are three kinds of strategies for memory allocation when the program runs, which are static, stacked, and stacked.

      Static storage allocation is the ability to determine at compile time the storage space requirements for each data target at run time, so that they can be allocated a fixed amount of memory at compile time. This allocation policy requires that the existence of mutable data structures (such as variable groups) not be allowed in the program code, and that nested or recursive structures are not allowed to appear. Because they all cause the compiler to not be able to calculate the exact storage space requirements.

      A stack storage allocation can also be called dynamic storage allocation, which is implemented by a stack-like run stack. In contrast to static storage allocation, in a stack storage scenario, the requirements for the data area are completely unknown at compile time, only to be known when running, but when the rules are entered into a program module You must know the size of the data area required by the program module to allocate memory for it. As with the stack we are familiar with in the data structure, the stack storage allocation is distributed according to the principle of advanced post-out.

      Static storage allocation requires that the storage requirements of all variables be known at compile time, and that the stack storage allocation requires that all storage requirements be known at the entrance of the process, while the heap storage allocation is specifically responsible for the memory allocation of the data structures that the storage requirements cannot be determined at compile-time or at runtime module entrances. such as variable-length strings and object instances. The heap consists of large chunks of available or free blocks, and the memory in the heap can be allocated and freed in any order.

    • Comparison of heaps and stacks

The above definition is summarized from the compiling principle of the textbook, in addition to static storage allocation, it is very inflexible and difficult to understand, the following aside static storage allocation, centralized comparison heap and stack:

From the heap and the function of the stack and the role of the popular comparison, the heap is mainly used to store objects, the stack is mainly used to execute the program. And this difference is mainly due to the characteristics of the heap and stack:

In programming, for example, C + +, all method calls are made through stacks, all local variables, and formal parameters that allocate memory space from the stack. It's actually not an assignment, just up the top of the stack, like a conveyor belt in the factory (conveyor belt), stack pointer will automatically guide you to where you put things, All you have to do is put things down. When you exit a function, you can destroy the contents of the stack by modifying the stack pointer. This mode is the fastest, of course, to run the program. It is important to note that when allocating a data area for a program module that is about to be called, The size of this data area should be known in advance, but it is said that although the allocation is carried out at the time of the program running, the size of the allocation is determined, unchanged, and the "size of how much" is determined at compile time, not at runtime.

Heap is when the application is running to request the operating system to allocate its own memory, because of the memory allocation from the operating system management, so the allocation and destruction of time, so the efficiency of the heap is very low. But the advantage of the heap is that the compiler does not have to know how much storage space to allocate from the heap. It is also not necessary to know how long the stored data will stay in the heap, so there is greater flexibility in storing the data with the heap. In fact, object-oriented polymorphism, heap memory allocation is essential, because the required storage space for polymorphic variables can only be determined after the object is created at run time. In C + +, when you require an object to be created, you only need to compile the relevant code with the new command. When you execute the code, the data is saved automatically in the heap. Of course, to achieve this flexibility, there is a certain price to pay: it will take longer to allocate storage space in the heap! This is the reason we have just said that the inefficiency of the reasons, it seems that comrade Lenin said good, people's advantages are often also human shortcomings, human shortcomings are often also the advantages of people (halo ~).

    • Heaps and stacks in the JVM

The JVM is a stack-based virtual machine. The JVM allocates a stack for each newly created thread. In other words, for a Java program, it runs through the operation of the stack. The stack holds the state of the thread in frames. The JVM operates on the stack in only two ways: stack and stack operations in frames.

We know that the method that a thread is executing is called the current method of this thread. We may not know that the frame used by the current method is called the current frame. When a thread activates a Java method, the JVM presses a new frame into the Java stack of threads. This frame naturally becomes the current frame. During the execution of this method, this frame is used to hold parameters, local variables, intermediate calculation procedures, and other data. This frame is similar to the concept of the activity record in the compilation principle.

From this allocation mechanism in Java, the stack can be understood as a stack is a storage area that the operating system establishes for a process, or a thread (a thread in a multithreaded operating system) for this thread, which has an advanced post-out feature.

Each Java application uniquely corresponds to a single JVM instance, and each instance uniquely corresponds to one heap. All instances or arrays of classes created by the application in the run are placed in this heap and shared by all threads of the application. Unlike C + +, allocating heap memory is automatically initialized in Java. The storage space for all objects in Java is allocated in the heap, but the reference to this object is allocated on the stack, that is, allocating memory from two places when an object is built, memory allocated in the heap actually establishes the object, and the memory allocated on the stack is just a pointer to the heap object (reference) Only.

Java load Order

The static initialization of the first class, then the initialization of the instance, and finally the execution of the construction method. That is, static initialization is a process of class loading, so it executes only once, and instance initialization is performed once per object creation, and the constructor is actually the same as the instance initialization, but it executes after the instance is initialized, and the construction method can overload multiple Which construction method to execute is based on your choice.

The emptying of the StringBuilder

The StringBuilder does not provide a clear or empty method.

There are 3 ways to clear:

1) Reborn into one, the old is automatically recovered by the system

2) Use Delete

3) Use SetLength

Cycle three methods 10 million times, code:

 1.public class SBBM {2.3.static String a;4.static long time; 5.public static void Main (string[] args) throws Exception {6.7. StringBuilder sb = new StringBuilder (); 8. StringBuilder SB3 = new StringBuilder (); 9.10.  Time = System.currenttimemillis (); 11.  for (int i = 0; i < 10000000; i++) {12.  StringBuilder SB2 = new StringBuilder (); 13.  Sb2.append ("somestr6ing"); 14.  Sb2.append ("Somes5tring2"); 15.  Sb2.append ("some3strin4g"); 16.  Sb2.append ("so3mestr5ing"); 17.  Sb2.append ("so2mest7ring"); 18.  A = Sb2.tostring (); 19.  }20.  System.out.println ("way2=" + (System.currenttimemillis ()-time)); 21. 22.23.time = System.currenttimemillis () 24.for (int i = 0; i < 10000000; i++) {25.sb.delete (0, Sb.length ()); 26.sb.ap Pend ("somestring"), 27.sb.append ("SomeString2"), 28.sb.append ("somestrin4g"), 29.sb.append ("somestr5ing"); 30. Sb.append ("somest7ring"); 31.a = Sb.tostring (); 32.} 33.system.out.println ("way1=" + (System.currenttimemillis ()-time)); 34.35.time = System.currenttiMemillis (); 36.for (int i = 0; i < 10000000; i++) {37.38.sb3.setlength (0); 39.sb3.append ("somestr55ing"); 40.sb3.appe nd ("some44string2"); 41.sb3.append ("som55estrin4g"); 42.sb3.append ("some66str5ing"); 43.sb3.append ("So33meSt7ring "); 44.a= sb3.tostring (); 45.} 46.system.out.println ("way3=" + (System.currenttimemillis ()-time)); 47. 48.49.} 50.}

Harvesting in the Java learning process

Related Article

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.