Invoke the original type and type

  Abstract: invoke the original type and type 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="261" height="86" align="center" valign="top"> </ td> <td width="423" valign="top"> 

  Java offers two different types: type and use the original type (or built-in type).    In addition, Java is also provided for each type of the original package category (Wrapper). 

  If you need an integer variable is the use of basic int type it, or to use an object such as Integer?    If you need to declare a boolean type, the use of basic boolean, or the use of Boolean type of an object?    This paper will help you make a decision. 

  Below is a list of the original object types as well as their packaging category.    î—± î—± 
  î—± î—± î—± primitive type of package î—± î—± boolean î—± î—± Boolean 
  î—± î—± char î—± î—± î—± î—± Character 
  î—± î—± byte î—± î—± î—± î—± Byte 
  î—± î—± short î—± î—± î—± î—± Short 
  î—± î—± int î—± î—± î—± î—± î—± Integer 
  î—± î—± long î—± î—± î—± î—± Long 
  î—± î—± float î—± î—± î—± î—± Float 
  î—± î—± double î—± î—± î—± Double 

  </ Td> </ tr> </ table> 

  î—± invoke the original type and type of conduct is totally different, and they have different semantics.    For example, assume that there are two methods of a local variable, a variable of type int original, and the other variable is the object of an Integer object quote: î—± 

  î—± int i = 5; / / primitive type 
  î—± î—± Integer j = new Integer (10); / / object reference 

  î—± î—± these two variables are stored in the local variables in the table, and a few are in the Java stack operation in the operation, but they said it's completely different.    (This article in the following sections will be used to replace the generic term stack operation of stack or local variables table.) 

  Int type and the original object reference each stack of 32.    (To express an int or an object reference, the Java Virtual Machine to use at least 32 storage.) Integer object of the stack is not the object itself, but an object reference.    Java to all objects in the object invoked visit.    Object reference refers to the object storage pile of a regional indicator.    When a primitive type of statement, the statement itself for the type of storage. 

  î—± î—± invoke the original type and the characteristics of different types and usage, including: size and speed to the type of data structure storage, when the decision to invoke the original type and type for a particular instance of the class specified in the data missing Province value.    Object variables cited examples of the default values for null, and the original type of instance variables with the default values of their types. 

  î—± î—± many procedural code will also contain the original object types, as well as their packaging.    When they check whether the same at the same time the use of these two types and the correct understanding of how they interact and coexistence will be a problem.    Programmers need to understand how these two types of work and interaction in order to avoid error code.  î—±

  î—±, for example, not the original type of call, but the call can be targeted: 

  î—± î—± int j = 5; 
  î—± î—± j.hashCode (); / / error 
  î—± î—± //… 
  î—± î—± Integer i = new Integer (5); 
  î—± î—± i.hashCode (); / / correct î—± î—± 

  Not the original call new type, there is no need to create objects.    This savings in time and space.    The mixed use primitive types, and objects may also lead to accidents with the results of the assignment.    Did not appear to have the wrong code may not be able to complete the work you want to do.    For example: 

  î—± î—± import java.awt.Point; 
  î—± î—± class Assign 
  î—± î—± ( 
  î—± î—± î—± public static void main (String args []) 
  î—± î—± î—± ( 
  î—± î—± int a = 1; 
  î—± î—± int b = 2; 
  î—± î—± Point x = new Point (0,0); 
  î—± î—± Point y = new Point (1,1); / / 1 
  î—± î—± System.out.println ( "a is the" + a); 
  î—± î—± System.out.println ( "b is" + b); 
  î—± î—± System.out.println ( "x is" + x); 
  î—± î—± System.out.println ( "y is" + y); 
  î—± î—± System.out.println ( "Performing assignment and" + "setLocation …"); 
  î—± î—± a = b; 
  î—± î—± a + +; 
  î—± î—± x = y; / / 2 
  î—± î—± x.setLocation (5,5); / / 3 
  î—± î—± System.out.println ( "a is the" + a); 
  î—± î—± System.out.println ( "b is" + b); 
  î—± î—± System.out.println ( "x is" + x); 
  î—± î—± System.out.println ( "y is" + y); 
  î—± î—± î—±) 
  î—± î—± î—±) 

  î—± This code generates the following output: 

  î—± î—± a is a 
  î—± î—± b is 2 
  î—± î—± x is java.awt.Point [x = 0, y = 0] 
  î—± î—± y is java.awt.Point [x = 1, y = 1] 
  î—± î—± Performing assignment and setLocation … 
  î—± î—± a is 3 
  î—± î—± b is 2 
  î—± î—± x is java.awt.Point [x = 5, y = 5] 
  î—± î—± y is java.awt.Point [x = 5, y = 5] î—± 

  î—± integers a and b to amend the results of the local no accident.    B is the value of a given integer variables, a result of the increased value of 1.    This output reflects our hope that happening.    However, it is surprising, in the assignment and call setLocation after x and y object output.    We have completed x = y assignment after a specially called setLocation the x, x and y values how will be the same?    After all, we will be given x y, then x changes, which we rounded a and b of the operation no different.    î—± î—± 

  The confusion is from the original type and the use of the object.    These two types of assignment of the role played by little different.    However, it may seem all different.    Assigned to equal (=) equivalent to the value of the left side of the right values.    This is the original type (such as in front of int a and b) is obvious.    For non-primitive types (such as Point object), the assignment is to amend object reference, and not object itself.    Therefore, in the words x = y;, x is y.    In other words, because the x and y is the object reference, they are now invoked with an object.    Therefore, the x will be any changes made changes y. 

  î—± î—± because x and y invoked with an object, so the implementation of the x and the y all means of implementation methods role on the same object. 

  î—± î—± distinction invoked the original type and type and use the semantic understanding is very important.    If this is not done, then the code will not complete the preparation of the work scheduled. 

  </ Td> </ tr> <tr> 

  ↑ Back 

Avoid restart your application

  Abstract: avoid restart your application 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="284" height="86" align="center" valign="top"> </ td> <td width="400" valign="top"> 

  In the development and testing stage, a certain functional modules mistakes or functional requirements change, this time programmers would normally modify the source code, and then recompiled, and stop applications, re-starting the application.    It then revised in the function is correct, whether or not meet the demand.    Well, all in the development and testing stage, no problems have understandable.    But to the application Zhengshishangxian appeared in trouble.    Application will lead to the resumption system can not be used, or lead to the request of users, loss of response.    Some even shape the system requirements of this dynamic additions to the system, in the absence of your application added to prevent the re-launch strategy, usually can do is to take advantage of users 2:00 less time you restart the application or temporarily switch to backup systems. 
  If you have encountered a system will be inevitable, or encountered such a problem, and that in this article, several solutions can be used for your choice. 

  1: Before the start, not the preservation and processing of the request to the user's response.    Better way is to receive requests, send your response to the processing module and the modules separate application logic design.    If the current web server, can you re-deployment (redploy) at the request of users temporarily stored in queues, wait until after the successful deployment submitted to the processing logic modules.    Also, receive requests, the module is sent response to different applications.    And the application logic modules through the document (the sequence into a document request), including the exchange of data, so that the logic of your application after the restart, it can still continue to read request 

  </ Td> </ tr> </ table> 


  Second: If the function is purely to update data, then use dynamic allocation, avoid restart.    For example, a web system to provide reloadConfig interface, re-read from the configuration file in the data.    A java application, you can process your application in the detection launch a thread, testing whether the document was changed, if the change will automatically re-loading configuration.    The following examples: 
  Public ConfigChecker extends Thread 
  ( 
  SystemManager sm = null; / / System Manager 
  Long time; 
  Public ConfigChecker (SystemManager sm) throws ApplicationException 
  ( 
  This.sm = sm; 
  Time = getConfigFileTime ();// access configuration file final modified 
  ) 
  Pulblic void run () 
  ( 

  While (! Interrupted ()) 
  ( 
  Try 
  ( 
  Long newTime = getConfigFileTime ();// access configuration file final modified 
  If (newTime! = Time) 
  ( 
  Time = newTime; 
  / / Reloading configuration 
  Sm.reloadConfig (); 

  ) 
  Thread.sleep (1000 * 3) 
  ) 
  Catch (Exception ex) 
  ( 
  Return; 
  ) 

  ) 
  ) 

  Public long getConfigFileTime () throws ApplicationException 
  ( 
  Try 
  ( 
  File f = new File (sm.getConfigFile ());// access configuration file 
  Return f.lastModified () / / return profile of the modified final 
  ) 
  Catch (IOException ex) 
  ( 
  Throw new ApplicationException (ex.getMessage ()) 
  ) 

  ) 
  ) 


  This way for you to dynamic change is pure data, it requires the application of data you can not write died in the code, but through configuration files.    Through re-read from the configuration file in the data to restart 

  3: If the updated features include application logic, which is to change the class, then a little trouble, you need to understand the principles of ClassLoader.    Use your custom ClassLoader Load has been re-compiled class can be compared to restart application you like.    Below will be brief ClassLoader principle, and cited an example to illustrate how to avoid reopening applications 


  Virtual Machine to carry through Classloader category.    Bootstrap loader is responsible for the class load jdk (java. *, javax .*), the system class loader is bootstrap subclass for the load all chasspath designated variables.    ClassLoader will flow into Class B category, byte stream may ↑ Back 

Abstract classes and interfaces distinction

  Abstract: An abstract class and interface differences 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="271" height="86" align="center" valign="top"> </ td> <td width="413" valign="top"> abstract class and interface Java is the language in the definition of the abstract class support of the two mechanisms, it is precisely because the existence of these two mechanisms, it has given a powerful object-oriented Java capability.    Abstract class and the interface between the abstract category in the definition of support is very similar, and even replace each other, many developers in the abstract definition of the abstract class, and the choice of interface is relatively arbitrary.    In fact, between the two there is still great difference, even for their choice reflects the nature of the problem areas for understanding, the understanding of the design intent is correct and reasonable.    In this paper, they will carry out the difference between a dissection, and attempt to provide developers with a choice between the two, basis. 

  Understand abstract class 

  Abstract class and interface in the Java language are used for abstract classes (This article is not in the abstract category come from the abstract class translation, it said that the body is an abstract, and abstract class for the Java language is used to define the abstract category a method to distinguish the attention of readers) definition, then what is an abstract class, the use of an abstract class can bring us any good? 
  </ Td> </ tr> <tr> <td height="14" colspan="2"> 

  </ Td> </ tr> </ table> 

  In the object-oriented concept, we know that all objects are described by type, but the contrary is not the case.    Not all categories are used to describe the object, if a class does not contain enough information to describe a specific target, such a class is an abstract class.    An abstract class is often used to our characterization of the problem areas in the analysis, design drawn abstraction is a series of looks different, but essentially the same concept of the abstract concrete.    For example: If we have a graphics editing software development, we will find that there are areas of circular, triangular this specific concept, they are different, but they also belong to the shape of such a concept, the concept of shape is not in the problem areas exist, it is an abstract concept.    It is precisely because the concept of abstract no counterpart in the field of the specific concept, used to describe abstract concept of an abstract class can not be the case. 

  In object-oriented fields, mainly used for abstract class type hide.    We can construct a fixed behavior of a group of abstract description, but this group is able to conduct arbitrary possible to achieve the specific way.    This is the abstract description of the abstract category, and this group of arbitrary possible a concrete realization of the performance for all possible derived class.    Modules can operate in an abstract.    Because the module relies on the abstract of a fixed, it can be modified; At the same time, from the abstract of this derivative, may also expand this module function.    Readers familiar with the OCP will be aware that in order to achieve the object-oriented design one of the most core principles OCP (Open-Closed Principle), an abstract class is one of the key. 


  Syntax definition from the perspective abstract class and interface 

  In the syntax level, the Java language interface and the abstract class is given a different definition, a definition below to the abstract class called Demo as an example to illustrate the difference. 

  Use the abstract class defined Demo abstract class in the following manner: 

  (Abstract class Demo 
  Abstract void method1 (); 
  Abstract void method2 (); 
…
  ) 

  The use interface Demo abstract class defined in the following manner: 

  (Interface Demo 
  Void method1 (); 
  Void method2 (); 
…
  ) 

  In the abstract class methods, Demo can have their own data members can be members of the non-abstarct approach, and the way in the implementation of the interface, Demo can only have static data can not be amended members (that is, must be static final , but generally not in the interface definition data members), all members of the methods are abstract.    In a sense, the interface is a special form of abstract class. 

  From the point of view of programming, the abstract class and the interface can be used to achieve the "design by contract" thinking.    However, in the use of concrete above or are there some distinction. 

  First, the abstract class in the Java language that is an inheritance, a class can only be used once inheritance.    However, a class can implement multiple interface.    Perhaps this is the designers of the Java language Java in considering support for multiple inheritance of a compromise to consider it. 

  Secondly, the definition of the abstract class, we can give the default behavior method.    However, in the definition of interface, but not with the default method, in order to circumvent this limitation, you must use commissioned, but it will be some additional complexity, and sometimes a lot of trouble. 

  In the abstract class can not be defined in the default behavior of still another more serious issue, which is likely to cause trouble maintaining.    If subsequently want to change the interface type (usually through abstract class or interface to express) to adapt to the new situation (for example, add a new method or methods have been used to add new parameters), will be very troublesome, may have to spend a lot of time (for many of the derived class, it is particularly the case).    However, if the interface is achieved through abstract class, then may only need to amend the definition of the abstract class in the default behavior on it. 

  Similarly, if not in the abstract class defined in the default behavior, it will lead to the same method appears in the abstract category in each derived class, in violation of the "one rule, one place" principle, resulting in duplication of code, and are not conducive to the future maintenance.    Therefore, in the abstract class and the interface between the choices to be very cautious. 


  Design Concept perspective from the abstract class and interface 

  Mainly from the above definition of syntax and programming perspective on the interface of the abstract class and distinction, the difference between these levels are relatively low level, the Feibenzhi.    This section will be another level: abstract class and interface design reflects the idea to an analysis of the difference between the two.    The writer believes that, from this level of the two can understand the essence of the concept. 

  As already mentioned, abstarct class in the Java language reflects a succession relations, in order to make reasonable inheritance, and the father of derived class must exist between "is a" relationship, that is, and the father of the concept of nature derived class should be the same (references in [3] on "is a" relationship of the length of the in-depth exposition, interested readers can reference).    , The interface is not, does not require interface and the realization of the concept of interface definition is essentially the same, only the realization of the interface definition of lease it.    In order to facilitate understanding discussed below will be through a simple example of a description. 

  Consider this an example, we assume that the problem areas, there is a Door on the abstract concept, with the implementation of the Door open and close the two movements, at this time we can abstract class or interface to the definition of an abstract concept that the type of definition of ways were as follows: 

  Use abstract class defined Door: 

  Abstract class Door ( 
  Abstract void open (); 
  Abstract void close (); 
  ) 


  Use interface defined Door: 


  (Interface Door 
  Void open (); 
  Void close (); 
  ) 


  Other specific types Door extends the use of abstract class can be defined using the Door or implements the interface defined Door.    Looks like interface and the use of abstract class does not have major differences. 

  If the request has to Door Alarm function.    How are we going to design for the structure of the examples of this category (in this case, is to display abstract class and interface design concept reflected in the difference between the other issues unrelated to have done to simplify or ignored)?    Luo listed below will be possible solutions, and design the conceptual level from these options for analysis. 

  Solution 1: 

  Door in the simple definition of an additional alarm, as follows: 

  Abstract class Door ( 
  Abstract void open (); 
  Abstract void close (); 
  Abstract void alarm (); 
  ) 


  Or 

  (Interface Door 
  Void open (); 
  Void close (); 
  Void alarm (); 
  ) 


  So with alarm function AlarmDoor the definition as follows: 

  (Class AlarmDoor extends Door 
  Void open () ()… 
  Void close () ()… 
  Void alarm () ()… 
  ) 


  Or 

  (Class AlarmDoor implements Door 
  Void open () ()… 
  Void close () ()… 
  Void alarm () ()… 
  ) 

  This measure violates the object-oriented design of a core principle ISP (Interface Segregation Priciple), Door to Door in the definition of the concept of inherent behavior methods and another concept "alarm" act together in the mixed method.    This is a problem caused by those who rely solely on the concept of the Door Module because of the "alarm" the concept of this change (for example: Amending alarm method parameters) changed, still the contrary. 

  Solution 2: 

  Since the open, close and alarm are two different concepts, according to the principle of ISP should be representative of their respective definitions of these two concepts in the abstract category.    Definition of ways: the use of these two concepts are abstract class defined; two concepts are defined to use interface and an abstract class concept of the use of defined, and the other concept of the use of defined interface. 

  Clearly, the Java language does not support multiple inheritance, the two concepts are defined using abstract class is not feasible.    Behind both are feasible, but it is their choice in the field of the problem reflects the essence of the concept of understanding, designed to reflect the correct and rational.    We January 1 to analyze that. 

  If the two concepts are used to define the interface mode, then reflects two problems: 1, we may not have a clear understanding of the field, AlarmDoor the concept is essentially in the end Door or alarm?    2, if we have no understanding of problem areas, such as: We have, through the analysis of problem areas found in the concept of nature AlarmDoor and Door is the same, so when we realize there is no right to expose our design intent, because In both the definition of the concept (use interface are defined) do not reflect the meaning. 

  If we understand the problem areas are: AlarmDoor the concept is essentially Door, at the same time it is the function of the police.    How are we going to design and realize that we have to clear the meaning?    Said earlier, the abstract class in the Java language that a succession, and inheritance, in essence, "is a" relationship.    Therefore Door concept, we should use abstarct class approach to the definition.    In addition, the alarm function is also AlarmDoor that it can complete the definition of the concept of the report, so the concept of alarm through the interface can be defined.    As follows: 

  Abstract class Door ( 
  Abstract void open (); 
  Abstract void close (); 
  ) 
  (Interface Alarm 
  Void alarm (); 
  ) 
  Class AlarmDoor extends Door implements Alarm ( 
  Void open () ()… 
  Void close () ()… 
  Void alarm () ()… 
  ) 


  This basically means to realize that we have a clear understanding of the problem areas, and correctly expose our design intent.    In fact, that is the abstract class "is a" relationship, and that the interface is "like a" relationship, we can choose as a basis, of course, because it is based on the understanding of the problem areas, such as: If we think that AlarmDoor the concept is essentially a warning, a Door at the same time, the function, then the above definition of a way to turn. 

  </ Td> </ tr> <tr> 

  ↑ Back 

Java puzzles? Characters

  Abstract: Java puzzles? Characters 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="286" height="86" align="center" valign="top"> </ td> <td width="398" valign="top"> 

  Puzzle 11: The last laugh 

  The following procedures will be printed out? 

  Public class LastLaugh (public static void main (String [] args) (System.out.print ( "H" + "a"); System.out.print ( 'H' + 'a');)) 

  You may think that this process will print HaHa.    The procedure seems to be two ways of H and a link, but you can see the virtual.    If you run this procedure, we will find that it is Ha169 print.    Why, then, it will have such an act? 

  </ Td> </ tr> <tr> <td height="20" colspan="2"> 

  </ Td> </ tr> </ table> 

  As we expect, one pair of System.out.print call Print is Ha: it is the parameters of expression "H" + "a" Obviously, it is implementing a string connected.    And the second on System.out.print call is another question.    The problem is that 'H' and 'a' is a literal character constants, because these two operations are not a few strings, so the implementation of the + operator is additive rather than a string connected. 

  Compiler constants in the expression of 'H' + 'a', it is known through the expansion of our original type-two with the operation of numerical character ( 'H' and 'a') upgraded to achieve numerical int the.    From char to int conversion of the broadening of the original 16 is the numerical zero char extended to the 32 int.    The 'H', char values are 72, and the 'a', char values are 97, therefore expression 'H' + 'a' is equivalent to 72 + int constants 97, or 169. 

  Language stand on the position of a number of similarities between the char and string is illusory.    Language is concerned that char is a 16-bit unsigned integer type of primitive - that's it.    On the class libraries, not so, the class library contains many char acceptable parameters, as Unicode characters and treatment methods. 

  Then you should be how to link characters?    You can use these libraries.    For example, you can use a string buffer: 

  StringBuffer sb = new StringBuffer (); sb.append ( 'H'); sb.append ( 'a'); System.out.println (sb); 

  Can do normal operation, but is very ugly.    In fact, we still have ways to avoid this by the way the Chita lengthy code.    You can ensure that at least one operation for a few strings to compulsory + operators connected to the implementation of a string operation, rather than a Adder operation.    This common usage with an empty string ( "") as a connecting sequence, as follows: 

  System.out.println ( "" + 'H' + 'a'); 

  This usage can ensure that the transition of expression have been to a string.    Although this was very useful, but is somewhat embarrassing, and it may cause some of its own confusion.    Can you guess the following statement will print what?    If you are not sure, then try: 

  System.out.print ( "2 + 2 =" + 2 +2); 

  If you are using the JDK 5.0, you can also use 

  System.out.printf ( "% c% c", 'H', 'a'); 

  In short, the use of the string connecting operators use extra caution.    + Operator if and only if its operation of at least one type String is only when the implementation of the string connecting operation; Otherwise, it is the implementation of the adder.    If the link is not a numerical string type, then you can have several options: 

  •   Preferences an empty string; 
  •   Will be the first to use String.valueOf explicit numerical converted into a string; 
  •   Use a string buffer; 
  •   Or if you use the JDK 5.0 can be used printf methods. 

  This also includes a puzzle to the language designers lesson.    Operator overloading, even in Java only to a limited extent by the support, it will still cause confusion.    Heavy connected to a string + operator and may have been cast is a mistake. 

  Puzzle 12: ABC 

  This puzzles to ask is a pleasant problem, the following procedures will be printed? 

  Public class ABC (public static void main (String [] args) (String letters = "ABC"; char [] = (numbers'1 ','2','3 '); System.out.println (letters + " easy as "+ numbers);))    We hope that this procedure may be printed out ABC easy as 123.    Unfortunately, it did not.    If you run it, they will discover that it is printing, such as ABC easy as [C @ 16f0472 such things.    Why is the output would be so ugly? 

  Despite the char is an integer types, but many libraries have a special deal with them, because char numerical characters is often said that instead of integers.    For example, a char values will be passed to the method println print out a Unicode characters instead of its digital code.    An array of characters by the same special treatment: the char [] println Heavy print version will be covered by an array of all the characters, and String.valueOf and StringBuffer.append the char [] Heavy duty version of the act is similar. 

  However, the string connecting operators in these methods have not been defined.    The operator is defined as the first operation of its implementation string, and then connect the two strings together.    , Including an array of object reference string conversion defined as follows [JLS 15.18.1.1]: 

  If cited as null, it will be converted to the string "null."    Otherwise, the implementation of the conversion is not like any parameter called the Object toString method invoked the same, but if the call is the result of toString method null, then used string "null" in place. 

  Then, in a non-air above char array toString method will be called to the kind of behavior?    Object array inherited from the toString method [JLS 10.7], standardized described: "returns a string that contains the object of their names, '@' symbol, and that object hash code of a non - Symbol hex integer "[Java-API].    Class.getName related to the normative description: char [] type of object called the method of the results of the string "[C."    Will link them together we created in the process of printing out that the ugly string. 

  There are two ways this can be revised procedures.    You can connect a call to the string before the explicit will be converted into an array of a string: 

  System.out.println (letters + "easy as" + String.valueOf (numbers));    Or, you can call decomposition System.out.println calls for the two to take advantage of the char [] println Heavy version: 

  System.out.print (letters + "easy as"); System.out.println (numbers);    Please note that these revised only you call the valueOf method println, and the heavy-duty version of the correct circumstances, be in normal operation.    In other words, they are strictly dependent on the compiler used an array of types. 

  Below the description of the procedures for this dependence.    It looks like the second described a concrete realization of the revised approach, but it is the output produced with the initial output generated by the process as ugly as it is called the Object println Heavy version, rather than char [ ] heavy-duty version. 

  Class ABC2 (public static void main (String [] args) (String letters = "ABC"; Object numbers = new char [] ('1 ','2','3 '); System.out.print (letters + "easy as"); System.out.println (numbers);))    In short, char array is not the string.    To a char array will be converted into a string, it is necessary to call String.valueOf (char []) method.    Some libraries in the method of delivery of an array of char string of similar support, usually is to provide a heavy-duty version of the Object methods and a char [] version of the heavy-duty, and after which we want to produce act. 

  The language designer lesson is: type char [] may be overwritten toString method, it contains an array of characters.    More generally, the array type may override the toString method should be to return to the content of a string array that. 

  Puzzle 13: farm 

  George Orwell's "Animal Husbandry Course (Animal Farm)," a book readers may remember that the old Colonel Declaration: "All animals are equal." Below the Java program trying to test the declaration.    Well, it will print out? 

  Public class AnimalFarm (public static void main (String [] args) (final String pig = "length: 10"; final String dog = "length:" + pig.length (); System.out. Println ( "Animals are equal : "+ == pig dog);))    Surface analysis of the procedure might think that it should be printed out Animal are equal: true.    After all, pig and dog are final type of string variables are initialized to their character of the "length: 10."    In other words, pig and dog was quoted string is and will always be their equivalent.    However, the == operator test is whether these two object reference is applied to the same object.    In this case, they are not applied to the same object. 

  You may know the type String constants is the compiler of the memory limit.    In other words, any two types of String constants expression, if identified is the same sequences of characters, then they will use the same object reference to that.    If constant expression to initialize pig and dog, then they will certainly point to the same object, but the dog is not initialized by the constant expression.    Since the language has been in constant expressions allow the operation to the limit, and method in which the call is not, then, this procedure should print Animal are equal: false, right? 

  Ah, in fact wrong.    If you run the program, you will find it printed only false, and not any other things.    It did not print Animal are equal:.    It will not print how this string literal constant?    After all, it is the correct print!    Puzzle 11 of the programme includes a mystery that: + operator, or whether the string is used to connect addition, it == operator than a high priority.    Therefore, the method println parameters are calculated in the following manner: 

  System.out.println (( "Animals are equal:" + pig) == dog);    Boolean expression of the value of this is of course false, it is the procedure by the print output. 

  One sure to avoid such a predicament: in the use of strings connecting operator, always will be non-trivial operation with a few brackets enclose.    More generally, when you can not determine whether you want the brackets, should be chosen and properly, they will enclose.    If you println statements like this compared to enclose part, it will have the desired output Animals are equal: false: 

  System.out.println ( "Animals are equal:" + (pig == dog));    Arguably, the process is still a problem. 

  If you can, you should not rely on the code in the string constants, limited memory mechanism.    Limited memory mechanism is designed to reduce the amount of memory virtual machine, it is not as a programmer can use a tool designed.    Like this puzzle shows, which will have a string constant expression is not always apparent. 

  Worse still is that if you rely on the code memory limit mechanism to bring about the correctness of operation, then you must be careful to understand what parameters must be the domain and limited memory.    Compiler will not help you to check these variables, because of the limited memory and limited use the same type of strings (String) said.    These limited because of the string in memory caused by the failure is a very difficult bug to detect. 

  In comparing object reference, you should be given priority in the use equals methods rather than == operator, unless you need to compare the logo object is not the object value.    Through the application of this lesson to our procedures, we are given the following statement println This is the way it should have.    Clearly, in this way the revised procedures, it will print out true: 

  System.out.println ( "Animals are equal:" + pig.equals (dog));    The puzzle of language designers have two lessons. 

  •   String connected priority and should not be the same additive.    This means that override + operator to implement the string connection is a problem, as mentioned in the 11 puzzles in the same. 
  •   There is, the type can not be modified, such as String, quoted the equivalence ratio of the equivalent of more people are confused about.    Perhaps == operator in the application can not be modified by the type of implementation should be compared.    To achieve this, a method is the == operator as equals simple method of writing, and provide a separate System.identityHashCode similar to the method used to implement the logo comparison. 

  Puzzle 14: Escape characters defeat 

  Below the use of the procedures of the two escaped Unicode characters, and they are using the hexadecimal code that Unicode characters.    So, this procedure would print? 

  Public class EscapeRout (public static void main (String [] args) (/ / \ u0022 is the double quotes escaped Unicode characters System.out.println ( "a \ u0022.length () + \ u0022b." Length ()) ;))    In the process of a very superficial analysis would think that it should be printed out 26, because the two pairs of quotes from "a \ u0022.length () + \ u0022b" logo string between a total of 26 characters. 

  A little in-depth analysis that will be the view that the procedure should be Print 16, because the two escaped Unicode characters each in the source file needs to six characters, but they only said that a string of characters.    Therefore, the string should be the appearance of it than to be short of its 10 characters.    If you run this procedure, we will find that things are not that far from the case.    It is neither 26 print is not 16 but 2. 

  The key to understanding this puzzle is to know: Java in the string literal constant escaped Unicode characters did not provide any special treatment.    Compiler in a variety of analytical procedures will sign before the first escaped Unicode characters transformed into that of the characters they [JLS 3.2].    Therefore, the first procedure escaped Unicode character as a single-character string literal constant ( "a") quotes the end, and the second escaped Unicode characters as another single-character string literal constant ( "b ") began quotes.    Printing is the expression "a." Length () + "b." Length (), or 2. 

  If the procedures are certainly hope that the author of such acts, the following statement will be more clearly: 

  System.out.println ( "a." Length () + "b." Length ());    More likely situation is that the author hopes will be two pairs of characters placed in quotation marks the internal string literal constant.    Escaped use Unicode characters you achieve this, but you can use escape sequences of characters to achieve [JLS 3.10.6].    One pair of quotation marks that the escape sequences of characters is a backslash followed behind a double quotation marks (\ "). If the initial proceedings in the Unicode character escape sequence with escaped characters to replace, it will print out the desired 16: 

  System.out.println ( "a \." Length () + \ "b." Length ());    Many of the characters have escaped the corresponding sequences of characters, including the single quotes (\ '), newline (\ n), tabs (\ t) and backslash (\ \).    You can literally character string literal constant constants and the use of escape sequences of characters. 

  In fact, you can use as octal escape characters special type of escape sequences of characters, any ASCII characters will be placed in a string literal constant character or a literal constant, but the best is to use ordinary the escape sequences of characters. 

  The general escaped character sequences and octal escape escaped Unicode characters than the characters much better, because different characters and Unicode escaped, escaped character sequences in the analytical procedures to be processed after all the symbols. 

  ASCII character set is the smallest public feature set, it only 128 characters, but there are more than 65,000 Unicode characters.    An escaped Unicode characters can be used only in the use of ASCII characters in the procedure to insert a Unicode characters.    Unicode characters escaped a precise equivalent to that of the characters in it. 

  Unicode character was designed to escape the programmers need to insert a source file can not be said of the characters in character set of circumstances.    They will be mainly used for non-ASCII characters placed identifier, string literal constant, literal character constants and Notes.    Occasionally, escaped Unicode characters also be used to look quite similar in a number of characters clearly labelled one of a certain, thereby increasing the clarity of procedures. 

  In short, in the literal character string and constants, we should give priority to the escape sequences of characters, and not escaped Unicode characters.    Unicode characters escaped because they could be compiled in a sequence which has been dealing with premature and cause confusion.    Do not use Unicode characters escaped to express ASCII characters.    And the characters in the string literal constant, we should use escape sequences of characters; literal constants for the addition of these circumstances, should be directly inserted into ASCII characters in the source document. 

  Puzzle 15: It is to turn the Hello 

  Below is a procedure known examples of the changes made after a little bit version.    Well, it will print out? 

  / ** * Generated by the IBM IDL-to-Java compiler, version 1.0 * from F: \ TestRoot \ apps \ a1 \ units \ include \ PolicyHome.idl * Wednesday, June 17, 1998 6:44:40 o'clock AM GMT +00:00 * / public class Test (public static void main (String [] args) (System.out.print ( "Hell"); System.out.println ( "o world");))    This puzzle looks quite simple.    The program includes two sentences, the first print Hell, and the second in the same line of print o world, which will effectively link the two strings in them.    Therefore, you might expect the program print Hello world.    But unfortunately, you have committed a wrong, in fact, it simply passed compiler. 

  The problem is that Notes of the third line, which includes the characters \ units.    These characters to backslash (\), as well as keeping up with the letter u in the beginning, and it (\ u) is a Unicode characters escape the beginning.    Unfortunately, these characters did not keep up with the back four hexadecimal number of places, thus escaping the Unicode characters are in conformation, and the compiler was refused a request procedures.    Unicode character must escape the structure is good, even if there is in the Note as well. 

  In the Note insert a good structure escaped the Unicode character is legitimate, but we have little reason to do so.    Sometimes programmers JavaDoc Notes will be used in the escape Unicode characters in the document with special characters. 

  / / Unicode escaped characters in the JavaDoc Notes in the usage / ** * This method calls itself recursively, causing a * StackOverflowError to be thrown. * The algorithm is due to Peter von der Ah \ u00E9 * /    The technology that has escaped Unicode characters a little utility usage.    Notes in the Javadoc, HTML entities should be used to replace the Unicode characters escaped escaped characters: 

  / ** * This method calls itself recursively, causing a * StackOverflowError to be thrown. * The algorithm is due to Peter von der Ahé * /    Two in front of the Notes should be in the document is the name "Peter der Ahé," but after a note in the source file is understandable. 

  Perhaps you would be very much surprised, in this puzzle, the problem of this information in the Notes ↑ Back 

Write composite model example of the binary tree

  Abstract: composite model examples of writing binary tree 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="198" height="86" align="center" valign="top"> </ td> <td width="486" valign="top"> 

  1, Component abstract components 
  Tree and Leaf succession Component 

  Private String name; / / tree leaves or the name of 

  AddChild (Component leftChild, Component rightChild); 
  / / Add a tree to the left of a child, a child right 
  GetName () (return name;) 
  GetTreeInfo () () / / or tree leaves have detailed information 
  GetLength (); / / be the height of the tree 

  2, Tree binary tree, a left child, a child right 

  3, Leaf is the leaf nodes 
  4, Test test node 

  / ** Component.Java **************/ 

  / ** Component.Java **************/ package binarytree; public abstract class Component (private String name; public abstract Component addChild (Component leftChild, Component rightChild); public String getName () (return name;) public void getTreeInfo () () public abstract int getLength ();) / ** Leaf.java **************/ package binarytree; public class Leaf extends Component ( private String name; private Component leaf = null; public Leaf (String name) (this.name = name;) 

  </ Td> </ tr> </ table> 

  Public Component addChild (Component leftChild, Component rightChild) (return this;) public String getName () (return name;) public int getLength () (return 1;) public static void main (String [] args) ()) / * * Tree.java **************/ package binarytree; public class Tree extends Component (private String name; private Component leftChild; private Component rightChild; public Tree (String name, Component leftChild, Component rightChild) (this.name = name; this.leftChild = leftChild; this.rightChild = rightChild;) public Tree (String name) (this.name = name; this.leftChild = null; this.rightChild = null;) public Component addChild (Component leftChild, Component rightChild) = (leftChild this.leftChild; this.rightChild = rightChild; return this;) public String getName () (return name;) public void getTreeInfo () / / or tree leaves have detailed information / / first print their names, left with the children all over again, all over again right of the child / / If children left or right child is the tree, recursive call (System.out.println ( "this trees name is" + getName ()) ; if (this.leftChild instanceof Leaf) (System.out.println (getName () + "s left child is" + this.leftChild.getName ()+", it is a Leaf ");) if (this.leftChild instanceof Tree) (System.out.println (getName () + "s left child is" + this.leftChild.getName ()+", it is a Tree "); this.leftChild.getTreeInfo ();) if (this . leftChild == null) (System.out.println (getName () + "s left child is a null");) if (this.rightChild instanceof Leaf) (System.out.println (getName () + "s right child is "+ this.rightChild.getName ()+", it is a Leaf");) if (this.rightChild instanceof Tree) (System.out.println (getName () + "s right child is" + this. rightChild.getName ()+", it is a Tree "); this.rightChild.getTreeInfo ();) if (this.rightChild == null) (System.out.println (getName () +" s right child is a null ");) / / System.out.println (getName () +" s height "+ getLength ());) public int getLength () (/ / child left or right compare the height of the child, who, + 1 / / the air if the child's treatment (this.leftChild == null) (if (this.rightChild == null) return 1; else return this.rightChild.getLength () +1;) else (if (this.rightChild == null) (return this.leftChild.getLength () +1;) else (if ((this.leftChild.getLength ())>=( this.rightChild.getLength ())) return this.leftChild.getLength () +1; else return this.rightChild.getLength () +1;))) public static void main (String [] args) ()) / ** Test.java test-class *********** *** / package binarytree; public class Test (public Test () () public static void main (String [] args) (Component tree = new Tree ( "luopeng"); Component leaf_child = new Leaf ( "luopeng1"); Component right_child = new Leaf ( "luopeng2"); tree = tree.addChild (leaf_child, right_child); / / tree = tree.addRightChild (right_child); tree.getTreeInfo (); Component tree1 = new Tree ( "luopeng2"); tree1.addChild (tree, leaf_child); tree1.getTreeInfo (); Component tree2 = new Tree ( "luopeng3"); tree2.addChild (tree, null); tree2.getTreeInfo (); Component tree4 = new Tree ( "luopeng4" ); tree4.addChild (null, tree); tree4.getTreeInfo (); System.out.println (tree4.getName () + "is the height of the" + tree4.getLength ());)) 

  Running Results: 

  C: \ java> java Test 
  This trees name is luopeng 
  Luopengs left child is luopeng1, it is a Leaf 
  Luopengs right child is luopeng2, it is a Leaf 

  This trees name is luopeng2 
  Luopeng2s left child is luopeng, it is a Tree 
  This trees name is luopeng 
  Luopengs left child is luopeng1, it is a Leaf 
  Luopengs right child is luopeng2, it is a Leaf 
  Luopeng2s right child is luopeng1, it is a Leaf 

  This trees name is luopeng3 
  Luopeng3s left child is luopeng, it is a Tree 
  This trees name is luopeng 
  Luopengs left child is luopeng1, it is a Leaf 
  Luopengs right child is luopeng2, it is a Leaf 
  Luopeng3s right child is a null 

  This trees name is luopeng4 
  Luopeng4s left child is a null 
  Luopeng4s right child is luopeng, it is a Tree 
  This trees name is luopeng 
  Luopengs left child is luopeng1, it is a Leaf 
  Luopengs right child is luopeng2, it is a Leaf 
  Luopeng4 height is 3 

  </ Td> </ tr> <tr> 

  ↑ Back 

You can be from any pages from the referer

  Abstract: you can be from what pages from the referer 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="194" height="86" align="center" valign="top"> </ td> <td width="490" valign="top"> 

  In the development of web procedures, and sometimes we need to be from what users are connected over the pages, which uses referer.    It is http protocol, and therefore, any web to develop the language can be achieved, for example, jsp is: 

  Request.getHeader ( "referer"); 

  _ Php is $ SERVER [ 'HTTP_REFERER']. 

  The other I do not, for example the (in fact, will not other languages).    That it used to do?    I will cite two examples: 

  1, even prevent bootlegging 

  For example, I am a software download site, the download page in the first, I used to judge Previous referer face is not their own sites, if not, that it was stolen even download your address. 

  2, the security of e-commerce sites 

  I submit important information such as credit card use referer pages is not to judge their previous site, if not, hackers could use their writing is a form to submit, in order to skip you in the Back javascript verification purposes. 

  Use referer attention: 

  If I were in the browser directly in the importation of referer pages, and return is null (jsp), that is to say referer only from other pages link to click on this page will have content. 

  I did an experiment, for example, in my referer a.jsp code, it is the Back-b.htm, is a c.htm with iframe pages, and it embedded in the a.jsp in the iframe .    I b.htm input in the browser address, and then click the link to c.htm, it is revealed that the results of b.htm, if I directly in the browser, the input is c.htm that shows the c.htm. 

  </ Td> </ tr> <tr> <td height="20" colspan="2"> 

  </ Td> </ tr> </ table> </ td> </ tr> <tr> 

  ↑ Back 

Java-based agent design patterns

  Abstract: Based on the Java proxy design patterns 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="279" height="86" align="center" valign="top"> </ td> <td width="405" valign="top"> I. Introduction 

  We go to market technology for their own machines add luxury accessories, like many DIYer find agents, because the agents get things where not only guaranteed quality, and price and customer service, will be much better.    Agents have been customers of the things they want, but also enjoy agents additional services and manufacturers through agents will be out to promote their own products and services can be some of the tasks to the sales agents to complete ( Of course, agents and vendors to share the risk, distribution of profits), so can he can spend more things in the design of the products and the production. 
  </ Td> </ tr> </ table> 

  In the United States, any enterprise in order to get products on the market forward selling agents must be a part of it, otherwise it will be illegal.    Appear in the commercial operation of the agents played a very key role.    Careless pull far away, the topic of conversation, come back to, in our object-oriented programming design, the agents will not have such a role?    Of this article, people will definitely not be said: No! 

  The article then follow the model to look at the wonders of agents it. 

  Second, definitions and classifications 

  Acting model in the design mode is defined as: to provide a target for other agents to control the object of this visit.    Said bluntly that, in some cases, the client does not want or can not directly invoke an object, and agents can target customers and play an intermediary between the target, can not be removed, see the content and services, or add additional services to the needs of customers . 

  So when to use proxy mode?    In the existing methods used by the original time and the need to improve or modify methods, to improve this time there are two options: to amend the original method to adapt to the current use, or use a "third party" method Calling the original method and the results of the method of a certain control.    The first method is a clear violation of "the expansion of open, closed on the revised" (opening and closing principles), but also in the original method may result in modification of the original function becomes blurred and diversified (the same as now diversified enterprises) , and use the second method can be more clear and functional, to the maintenance of the back.    So to a certain extent, the second approach is a better choice. 

  Of course, Huayoushuihuilai, if it is a small system, function is not very complicated, then use a proxy model may seem cumbersome, as a way to the first of the fast.    This is like a three homes, household chores or by the housewife to complete a nanny is more reasonable, it does not need nanny employed in several layers of agents:) 

  According to the "Java and model," in the classification of the proxy mode, agent model is divided into eight kinds, will be here several common and important are listed below: 

  1. Remote (Remote) agents: a different address space in the target to provide a local representative objects.    For example: You can be a corner somewhere in the world a false impression of the machine through a proxy as a part of your LAN. 

  2. Virtual (Virtual) agents: the need to consume a lot of resources or more complicated objects delayed when the real needs of the creation.    For example: If a big picture, the need to spend a very long time to show up, then when the picture contained in the document, the use of the editor or browser to open this document, the big picture may affect the file reading , then Proxy picture needs to be a substitute for real picture. 

  3. Protection (Protect or Access) Agent: control of the access to an object.    For example: in the forums, landing different identities, has a different mandate, the use of proxy mode can be controlled authority (of course, also use can be achieved in other ways). 

  4. Smart references (Smart Reference) agent: the target audience than additional services.    For example: the flow of records access (this is a more simple example), provide some Tips and so on. 

  Acting model is a more useful model, from several categories of "small structure" to the huge system of "structure" can be seen its shadow. 

  Third, the structure 

  Acting in the mode of "agent" in order to achieve agent tasks, we must be agents and "manufacturers" use of a common interface (you can imagine for products).    So naturally you think of java in the use of an abstract class or interface (recommended) to achieve this common interface.    Acting alone model was composed of three roles: 

  1.    The role of abstract themes: the actual theme of the statement and the common theme agent interface. 

  2.    Acting role theme: internal contains references to reality theme, and provide real theme and the role of the same interface. 

  3.    Reality theme roles: the real definition of the object. 

  Use of graphs to show that the relations among the three as follows: 


  Of course, shown on the map is a model agent specific circumstances.    The agent model can be very flexible to use other means to achieve this on the map and shown to be much different. 

  Perhaps now you have agents already have a macro mode awareness, Below we look at how the actual use of proxy mode. 

  4, for example 

  Forum to have registered users and visitors authority as a different example: registered users have posting revise its own registration information, revise its own posts, and other functions and tourists can only see the posts of others, no other authority.    To simplify the code, a better model showed agents of the skeleton, we realize here only posting authority control.    First of all, we first achieve an abstract theme of the role of MyForum, define the true theme and the theme of the common interface agents - posting function. 

  Code as follows: 

  Public interface MyForum 

  ( 

  Public void AddFile (); 

  ) 

  Thus, the real theme of the role and the role of agent theme to achieve this interface.    The theme of the role of truth is the basic method of this interface content filled come.    Therefore, it will not repeat them here as well.    We concentrate on the main theme of the key roles of agents.    Acting general theme of the role of the code as follows: 

  Public class MyForumProxy implements MyForum 
  ( 
  Private RealMyForum forum; 
  Private int permission; / / Privilege value 

  Public MyForumProxy (int permission) 
  ( 
  Forum = new RealMyForum () 
  This.permission = permission; 
  ) 

  / / Interface Implementation 

  Public void AddFile () 
  ( 
  / / Set the time to meet authority will be able to run operations 
  / / Is a constant type Constants 
  If (Constants.ASSOCIATOR == permission) 
  ( 
  Forum.AddFile (); 
  ) 
  Else 
  System.out.println ( "You are not a associator of MyForum, please registe!"); 
  ) 
  ) 

  Acting on the realization of this model functions.    Of course, you can also add the Agency their own methods to achieve additional services, such as the number of visits to statistics posted record user's login and more. 

  Another very common example of the use of proxy mode on the large picture here is the control.    In our common site visit by the above information, I do not know you have noted that the picture here is a narrow place, when people have to carefully read this picture, you can activate by clicking on the picture to a link, in a new website opened depends on the picture.    This for improving the speed here is very good, because not everyone has to carefully look at the map information.    This situation can use a proxy model to the full realization.    Here, I will express ideas out, as realized as a result of reasons, not stated as such in the way of B / S mode feasibility of the true, I do not have confirmation, but was just abstract thought.    If it is not feasible, then the case can be placed in a C / S down in, this is absolutely no problem and, in many design patterns on the use of books and articles.    Two ways of achieving interested can come to give it a try. 

  We visited in the browser page is called the loading picture is not true method, but the method of targeting agents, in this object, the first thread to use a browser loading a diminished version of the picture, and background to the use of another thread calls the real big picture loading methods will be loaded into the local picture, and when you want to view the picture at its new website in the show.    Of course, if you want to browse the picture has not loaded when successful, can start a thread to display messages until loading success. 

  This proxy mode functionality embodied in the head in the above - through a proxy to the real picture will be loaded into the background to the operation, it does not affect the prospects here. 

  V. GENERAL 

  Acting model can be coordinated call and call, to a certain extent, reduce the coupling of the system.    But we must remember that in front of the use of Agent model stresses the conditions, otherwise the use of the agent model will not have good results, perhaps also the problem 

  </ Td> </ tr> <tr> 

  ↑ Back 

Depth-first search and breadth-first search

  Abstract: The depth-first search and breadth-first search 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="483" height="86" align="center" valign="top"> 

  First, depth-first search 
  Depth-first search is in the search tree each layer has expanded to only a subset of nodes, and continuing to advance the further progress until no longer (at leaf nodes or depth limit), only from the current node to return to the previous level nodes, along the other direction and continue to move forward.    This method is the search tree roots from the beginning of an evolving one. 

  Depth-first search is also known as the vertical search.    As the issue of a broken tree branch may contain infinite, if the depth-first search of potential infinite branches (that is, infinite depth), it is impossible to find the target node.    Therefore, the depth-first search strategy is not complete.    In addition, the application of this strategy are the solution is not necessarily optimal solution (Shortest Path). 

  Second, rearrangement Jiugong quiz 
  In a 3 x 3 Jiugong 1-8 in the eight and the number of randomly placed in a box which the grid yard.    As shown below left.    Now demands of the question: the Jiugong adjusted as follows in the form shown in Figure Right.    Adjustment rules: Each box will be (on the left or right) of the provisional figures-moved to a box.    Test programming. 

  | 2 | 8 | 3 | | 1 | 2 | 3 | 
  – 
  | 1 | | 4 | | 8 | | 4 | 

  | 7 | 6 | 5 | | 7 | 6 | 5 | 

  Depth-first search path diagram: 

  </ Td> <td width="201" valign="top"> </ td> </ tr> <tr> <td height="20" colspan="2"> 

  </ Td> </ tr> </ table> 

  Third, BFS 

  In the depth-first search algorithm, the greater the depth is the first node expanded.    If the search algorithm to the node according to the level of search, the layer nodes not dealing with the search, not the lower node processing, that is, the smaller the depth of the first node be expanded, that is to say The first node can be expanded to deal with, such as breadth-first search algorithm search method. 

  BFS path diagram: 

  Four flights (from "The Art of Java") 
  A customer to a scheduled from New York to Los Angeles flight tickets Below are the flight line, you look for a discount to customers programmes. 

  <table Width="581" border="1"> <tr> <td width="262"> flights </ td> <td width="303"> distance </ td> </ tr> <tr> < td> New York to Chicago </ td> <td> 900 miles </ td> </ tr> <tr> <td> Chicago to Denver </ td> <td> 1,000 miles </ td> </ tr> < tr> <td> New York to Toronto </ td> <td> 500 miles </ td> </ tr> <tr> <td> New York to Denver </ td> <td> 1,800 miles </ td> < / tr> <tr> <td> Toronto to Calgary </ td> <td> 1,700 miles </ td> </ tr> <tr> <td> Toronto to Los Angeles </ td> <td> 2,500 miles </ td> </ tr> <tr> <td> Toronto to Chicago </ td> <td> 500 miles </ td> </ tr> <tr> <td> Denver to Urbana </ td> <td> 1,000 miles </ td> </ tr> <tr> <td> Denver to Houston </ td> <td> 1,000 miles </ td> </ tr> <tr> <td> Houston to Los Angeles </ td> <td > 1,500 miles </ td> </ tr> <tr> <td> Denver to Los Angeles </ td> <td> 1,000 miles </ td> </ tr> </ table> 

  Below are using depth-first search for the procedure: 

  / / Find connections using a depth-first search. Import java.util .*; import java.io. *; / / Flight information. Class FlightInfo (String from; String to; int distance; boolean skip; / / used in backtracking FlightInfo (String f, String t, int d) (f = from; to = t; distance = d; skip = false;)) (class Depth final int MAX = 100; / / This array holds the flight information. FlightInfo flights [] = new FlightInfo [MAX]; int numFlights = 0 / / number of entries in flight array Stack btStack = new Stack (); / / backtrack stack public static void main (String args []) (String to and from; Depth ob = new Depth (); BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); ob.setup (); try (System.out.print ( "From?"); from br.readLine = () ; System.out.print ( "To?"); to br.readLine = (); ob.isflight (from, to); if (ob.btStack.size ()! = 0) ob.route (to); ) catch (IOException exc) (System.out.println ( "Error on input.");)) / / Initialize the flight database. void setup () (addFlight ( "New York" and "Chicago", 900); addFlight ( "Chicago" and "Denver", 1000); addFlight ( "New York" and "Toronto", 500); addFlight ( "New York", "Denver", 1800); addFlight ( "Toronto", "Calgary" 1700); addFlight ( "Toronto", "Los Angeles", 2500); addFlight ( "Toronto", "Chicago", 500); addFlight ( "Denver", "Urbana," 1000); addFlight ( "Denver," " Houston, "1000); addFlight (" Houston, "" Los Angeles ", 1500); addFlight (" Denver "," Los Angeles ", 1000);) / / Put flights into the database. void addFlight (String from, String to, int dist) (if (numFlights <MAX) (flights [numFlights] = new FlightInfo (from, to, dist); numFlights + +;) else System.out.println ( "Flight database full \ n");) / / Show the route and total distance. void route (String to) (Stack rev = new Stack (); int dist = 0; FlightInfo f; btStack.size int num = () / / Reverse the stack to display route. for (int i = 0; i <num; i + +) rev.push (btStack.pop ()); for (int i = 0; i <num; i + +) (f = (FlightInfo) rev.pop (); System. out.print (f.from + "to"); dist + = f.distance;) System.out.println (to); System.out.println ( "Distance is" + dist);) / * If there is a flight between from and to, and return the distance of flight; otherwise, return 0 * / int match (String from, String to) (for (int i = numFlights-1; i> 1; i -) (if (flights [i]. from.equals (from) & & flights [i]. to.equals (to) & &! flights [i]. skip) (flights [i]. skip = true; / / prevent reuse return flights [ i]. distance;)) return 0; / / not found) / / Given from, find any connection. FlightInfo find (String from) (for (int i = 0; i <numFlights; i + +) (if (flights [i ]. from.equals (from) & &! flights [i]. skip) (FlightInfo f = new FlightInfo (flights [i]. from, flights [i]. to, flights [i]. distance); flights [i] . skip = true; / / prevent reuse return f;)) return null;) / / Determine if there is a route between from and to. void isflight (String from, String to) (int dist; FlightInfo f; / / See if at destination. dist = match (from, to); if (dist! = 0) (btStack.push (new FlightInfo (from, to, dist)) return;) / / Try another connection. f = find (from ); if (f! = null) (btStack.push (new FlightInfo (from, to, f.distance)); isflight (f.to, to);) else if (btStack.size ()> 0) (/ / Backtrack and try another connection. f = (FlightInfo) btStack.pop (); isflight (f.from, f.to);))) 

  Explained: isflight () method using recursive method of depth-first search, which calls first match () method checks the flight database, and to judge from in between flights up there.    If so, the goal of obtaining information, and the line pressure Ruzhan, and then return (to find a programme).    Otherwise, we will find call () method View from arbitrary and other cities between the lines, if found return to a description on the line FlightInfo object, or return null.    If the existence of such a line, then put the lines kept in f, and the current flight information pressure to the top of the stack, and then recursive calls isflight () method, then stored in f.to in a new city the starting city. otherwise a regression, the first pop-up Zhanding nodes, and then recursive calls isflight () method.    The process will continue till the objective to find. 

  Running Results: 

  C: \ java> java Depth 
  From? New York 
  To? Los Angeles 
  New York to Chicago to Denver to Los Angeles 
  Distance is 2900 

  C: \ java> 

  Depth-first search to find a solution, at the same time, above this particular issue, depth-first search had not been rolled back, and once found a solution, but if the data organized in a manner different from when the solution is likely to find a number of regression.    Therefore, the example of the output is not universal.    Moreover, in a very long search, but which do not have a branch of the solution, depth-first search performance will be poor, in such circumstances, not only in the depth-first search of the search path, a waste of time, but also Back to the goals of a waste of time. 

  Look at the example of the use of this breadth-first search procedures: 

  / / Find connections using a breadth-first search. Import java.util .*; import java.io. *; / / Flight information. Class FlightInfo (String from; String to; int distance; boolean skip; / / used in backtracking FlightInfo (String f, String t, int d) (f = from; to = t; distance = d; skip = false;)) (class Breadth final int MAX = 100; / / This array holds the flight information. FlightInfo flights [] = new FlightInfo [MAX]; int numFlights = 0 / / number of entries in flight array Stack btStack = new Stack (); / / backtrack stack public static void main (String args []) (String to and from; Breadth ob = new Breadth (); BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); ob.setup (); try (System.out.print ( "From?"); from br.readLine = () ; System.out.print ( "To?"); to br.readLine = (); ob.isflight (from, to); if (ob.btStack.size ()! = 0) ob.route (to); ) catch (IOException exc) (System.out.println ( "Error on input.");)) / / Initialize the flight database. void setup () (addFlight ( "New York" and "Chicago", 900); addFlight ( "Chicago" and "Denver", 1000); addFlight ( "New York" and "Toronto", 500); addFlight ( "New York", "Denver", 1800); addFlight ( "Toronto", "Calgary" 1700); addFlight ( "Toronto", "Los Angeles", 2500); addFlight ( "Toronto", "Chicago", 500); addFlight ( "Denver", "Urbana," 1000); addFlight ( "Denver," " Houston, "1000); addFlight (" Houston, "" Los Angeles ", 1500); addFlight (" Denver "," Los Angeles ", 1000);) / / Put flights into the database. void addFlight (String from, String to, int dist) (if (numFlights <MAX) (flights [numFlights] = new FlightInfo (from, to, dist); numFlights + +;) else System.out.println ( "Flight database full \ n");) / / Show the route and total distance. void route (String to) (Stack rev = new Stack (); int dist = 0; FlightInfo f; btStack.size int num = () / / Reverse the stack to display route. for (int i = 0; i <num; i + +) rev.push (btStack.pop ()); for (int i = 0; i <num; i + +) (f = (FlightInfo) rev.pop (); System. out.print (f.from + "to"); dist + = f.distance;) System.out.println (to); System.out.println ( "Distance is" + dist);) / * If there is a flight between from and to, and return the distance of flight; otherwise, return 0 * / int match (String from, String to) (for (int i = numFlights-1; i> 1; i -) (if (flights [i]. from.equals (from) & & flights [i]. to.equals (to) & &! flights [i]. skip) (flights [i]. skip = true; / / prevent reuse return flights [ i]. distance;)) return 0; / / not found) / / Given from, find any connection. FlightInfo find (String from) (for (int i = 0; i <numFlights; i + +) (if (flights [i ]. from.equals (from) & &! flights [i]. skip) (FlightInfo f = new FlightInfo (flights [i]. from, flights [i]. to, flights [i]. distance); flights [i] . skip = true; / / prevent reuse return f;)) return null;) / * Determine if there is a route between from and to using breadth-first search * / void isflight (String from, String to) (int dist , dist2; FlightInfo f; / / This stack is needed by the breadth-first search. Stack resetStck = new Stack (); / / See if at destination. dist = match (from, to); if (dist! = 0) (btStack.push (new FlightInfo (from, to, dist)) return;) / * Following is the first part of the breadth-first modification. It checks all connecting flights from a specified node * / while ((f = find (from))! = null) (resetStck.push (f) if ((dist = match (f.to, to))! = 0) (resetStck.push (f.to); btStack.push (new FlightInfo (from, f.to, f.distance)); btStack.push (new FlightInfo (f.to, to, dist)) return;)) / * The following code resets the skip fields set by preceding while loop. This is also part of the breadth-first modifiction * / int i = resetStck.size (); for (; i! = 0; i -) resetSkip ((FlightInfo) resetStck.pop ()) / / Try another connection. f = find (from); if (f! = null) (btStack.push (new FlightInfo (from, to, f.distance)); isflight (f.to, to);) else if (btStack.size ()> 0) (/ / Backtrack and try another connection. f = (FlightInfo) btStack.pop (); isflight (f.from, f.to);)) / / Reset skip field of specified flight. void resetSkip ( FlightInfo f) (for (int i = 0; i <numFlights; i + +) if (flights [i]. from.equals (f.from) & & flights [i]. to.equals (f.to)) flights [i ]. skip = false;)) 

  Running Results: 

  C: \ java> java Breadth 
  From? New York 
  To? Los Angeles 
  New York to Toronto to Los Angeles 
  Distance is 3000 

  C: \ java> 

  It found a reasonable solution, but it does not have general.    Because the first of the path to find information on the physical forms of organization. 

  If the target in the search space is not too deep in hiding, then BFS performance will be very good. 

  </ Td> </ tr> <tr> 

  ↑ Back 

Send spam messages to the Web site

  Abstract: sending spam messages to the Web site 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="339" height="257" align="center" valign="top"> </ td> <td width="345" valign="top"> 

  / ** 
  File Name: HttpPost.java 
  Description: There is a Web site to keep me Email, and so they wrote a small program to automatically insert data inside the Message Author: Ciqi strong 
  Email: cqq1978@Gmail.com 
  ** / 

  Import java.net .*; 
  Import java.io. *; 
  (Class HttpPost extends Thread 
  Private String strUrl; 
  Private String strPostData; 

  Public void setUrl (String str) ( 
  StrUrl = str; 
  ) 

  </ Td> </ tr> </ table> 

  Public String getUrl () 
  ( 
  Return strUrl; 
  ) 
  Public void setPostData (String str) 
  ( 
  StrPostData = str; 
  ) 
  Public String getPostData () 
  ( 
  Return strPostData; 
  ) 
  Public void doHttpPost () 
  ( 
  String s, s1; 
  S = getUrl (); 
  S1 = getPostData (); 
  If (s! = Null) 
  ( 
  Try 
  ( 
  URL url = new URL (s); 
  URLConnection conn = url.openConnection (); 
  Conn.setDoOutput (true); 
  OutputStreamWriter wr = new OutputStreamWriter (conn.getOutputStream ()); 
  Wr.write (s1); 
  Wr.flush (); 
  BufferedReader rd = new BufferedReader (new InputStreamReader (conn.getInputStream ())); 
  Wr.close (); 
  Rd.close (); 
  ) 
  Catch (Exception e) 
  ( 
  System.out.println (e.toString ()); 
  ) 
  ) 
  ) 

  Public void run () 
  ( 
  For (int i = 1; i <20; i + +) 
  ( 
  HttpPost hp = new HttpPost (); 
  Hp.setUrl ( "http://www.hdptex.com/liuyan/savedata.asp"); 
  Hp.setPostData ( "txtname Maoshan Road flyover & txtEmail = = = s & txtTitle can not see txtContent = & http://blog.csdn.net/cqq"); 
  Hp.doHttpPost (); 
  System.out.println ( "" + i); 
  ) 
  ) 

  Public static void main (String [] args) 
  ( 
  Try 
  ( 
  Thread [] t = new Thread [2]; 
  For (int i = 0; i    ( 
  T [i] = new HttpPost (); 
  T [i]. Start (); 
  ) 
  ) 
  Catch (Exception e) 
  ( 
  System.out.println (e.toString ()); 
  ) 
  ) 
  ) 


  </ Td> </ tr> <tr> 

  ↑ Back 

String_getBytes () method in the Chinese coding problems

  Abstract: String_getBytes () method in the Chinese coding problems 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="684" height="20"> 

  String of getBytes () method is given a string array of bytes, which is well known.    However, with particular attention to is that this method will return to the operating system default encoding format of the byte array.    If you use this method does not take this into account, you will find a good platform to run on the system, put it in another machine will produce unexpected problems.    For example, the following procedures: <table width="675" border="0"> <tr> <td width="394"> 

  1.   Class TestCharset 
  2.   ( 
  3.   Public static void main (String [] args) 
  4.   ( 
  5.   New TestCharset (). Execute (); 
  6.   ) 
  7.   Private void execute () ( 
  8.   String s = "Hello! Hello!"; 
  9.   Byte [] bytes = s.getBytes (); 
  10.   System. Out.println ( "bytes lenght is:" + bytes. Length); 
  11.   ) 
  12.   ) 
  </ Td> <td width="271"> </ td> </ tr> </ table> 

  In a Chinese WindowsXP system, the run-time, results were as follows: 
  Bytes lenght is: 12 

  But if English has been put on a UNIX operating environment: 
  $ Java TestCharset 
  Bytes lenght is: 9 

  If you rely on the results of procedures, in the follow-up operation will cause problems.    Why, in a system in the results for 12, and in addition has turned out to a 9?    Already mentioned, the method is and platforms (code) related.    In the Chinese operating system, getBytes method is a return of the Chinese GBK or GB2312 encoded byte array, including Chinese characters, each with two bytes.    In English platform, the general default coding is "ISO-8859-1", each byte characters only take one (regardless of whether the non-Latin characters). 

  Java support in the coding 


  Java is the support for multi-country code, in Java, Unicode characters are stored, for example, "you" Unicode character encoding is "f60", we can test the adoption of the following code to verify: 
  1.   Class TestCharset 
  2.   ( 
  3.   Public static void main (String [] args) 
  4.   ( 
  5.   Char c = 'you'; 
  6.   Int i = c; 
  7.   System. Out.println (c); 
  8.   System. Out.println (i); 
  9.   ) 
  10.   ) 

  Whether you on all platforms, will have the same output: 

  —————— —————– Output 
  You 
20320

  20,320 is Unicode "4f60" integer values.    In fact, you can decompile the above categories can be found in the generated. Class characters in the document "you" (or any other Chinese string) itself is stored in Unicode encoding: 
  1.   Char c = '\ u4F60'; 
  2.   … … 

  Even if you know the code encoding formats, such as: 
  Javac-encoding GBK TestCharset.java 
  After the compiler generated. Class document storage format is still Unicode Chinese characters or strings. 

  Use String.getBytes (String charset) method 


  Therefore, in order to avoid such problems, I suggest that you use in coding String.getBytes (String charset) method.    Below we were extracted from the string ISO-8859-1 encoding formats and GBK two byte array and see what the outcome will be: 
  1.   Class TestCharset 
  2.   ( 
  3.   Public static void main (String [] args) 
  4.   ( 
  5.   New TestCharset (). Execute (); 
  6.   ) 
  7.   Private void execute () ( 
  8.   String s = "Hello! Hello!"; 
  9.   BytesISO8859 byte [] = null; 
  10.   BytesGBK byte [] = null; 
  11.   Try 
  12.   ( 
  13.   BytesISO8859 = s.getBytes ( "iso-8859-1"); 
  14.   BytesGBK = s.getBytes ( "GBK"); 
  15.   ) 
  16.   Catch (java.io. UnsupportedEncodingException e) 
  17.   ( 
  18.   E.printStackTrace (); 
  19.   ) 
  20.   System. Out.println ("————– \ n 8859 bytes: "); 
  21.   System. Out.println ( "bytes is:" + arrayToString (bytesISO8859)); 
  22.   System. Out.println ( "hex format is:" + encodeHex (bytesISO8859)); 
  23.   System. Out.println (); 
  24.   System. Out.println ("————– \ n GBK bytes: "); 
  25.   System. Out.println ( "bytes is:" + arrayToString (bytesGBK)); 
  26.   System. Out.println ( "hex format is:" + encodeHex (bytesGBK)); 
  27.   ) 
  28.   Public static final String encodeHex (byte [] bytes) ( 
  29.   StringBuffer buff = new StringBuffer (bytes. length * 2); 
  30.   String b; 
  31.   For (int i = 0; i    Length; i + +) 
  32.   ( 
  33.   B = Integer. ToHexString (bytes [i]); 
  34.   / / Byte is two bytes, and the above Integer.toHexString will be extended to four bytes bytes 
  35.   Buff.append (b. length ()> 2? B.substring (6,8): b); 
  36.   Buff.append ( ""); 
  37.   ) 
  38.   Return buff.toString (); 
  39.   ) 
  40.   Public static final String arrayToString (byte [] bytes) ( 
  41.   StringBuffer buff = new StringBuffer (); 
  42.   For (int i = 0; i    Length; i + +) 
  43.   ( 
  44.   Buff.append (bytes [i] + ""); 
  45.   ) 
  46.   Return buff.toString (); 
  47.   ) 
  48.   ) 
  Implementation of this program will print out: 
  1. ————–
  2.   8859 bytes: 
  3.   Bytes is: 7210110810811133 63 63 63 
  4.   Hex format is: 48 65 6c 6c 6f 21 3f 3f 3f 
  5. ————–
  6.   GBK bytes: 
  7.   Bytes is: 7210110810811133 -60 -29 -70 -61 -93 -95 
  8.   Hex format is: 48 65 6c 6c 6f 21 c4 e3 ba c3 a3 a1 

  Thus, even in the extraction of 8859-1 s format for the length of the array of bytes 9, Chinese characters have become "63", ASCII code 63 is a "?", Some foreign procedures in the Chinese domestic operating environment , often garbled, full of the above "?", it is because the code does not correctly deal with the results.    And the extraction of GBK encoded byte array in the correct Chinese characters have been GBK coding.    Characters "you", "good" and "!" GBK code are: "c4e3" "bac3" "a3a1."    Have the right to GBK encoded byte array, reducing the need for future Chinese string, you can use the following method: 
  New String (byte [] bytes, String charset) 

  The article ↑ Back 

keep looking »