Basic variable

All objects that come out of new are stored in the heap. For small and simple variables, new is often not very efficient. Instead, create an “automatic” variable that is not a reference and stores the “value” directly on the stack.

Primitive types have wrapper classes that allow you to create an object in the heap that represents the corresponding primitive type.

An array of

Java ensures that an array is initialized (zero or NULL) and cannot be accessed outside its scope, otherwise a runtime exception is thrown. When you create an array object, for example, you create an array of references. Each reference is initially null, and the compiler can clear all memory used by arrays of primitive data types.

No matter use what kind of array, the array identifier is just a reference, to create a real object in the heap, the array object is used to save references to other objects, object arrays and basic types in use is almost the same, there is only one difference between an array of objects are stored reference, basic types of array directly save values of basic types. The read-only member length is the only accessible field of the array object and indicates how many elements the array object can store, not the actual number of elements.

A multidimensional array is essentially a nested array. The high-dimensional elements maintain a low-microarray, and the number and memory of the low-microarray are allocated and managed by themselves

In Java, arrays are the most efficient way to store and randomly access sequences of object references. An array is a simple linear sequence, which makes element access very fast, but the price for this speed is that the size of the array object is fixed and immutable throughout its life.

With the advent of auto-wrapping, containers can now be used almost as easily with primitive types as arrays. Arrays have the sole advantage of being efficient, but arrays can be too restrictive to solve more general problems, so you’ll still use containers in those cases.

string

Strings are immutable. Every method in the String class that appears to modify the value of a String actually creates a new String containing the modified contents of the String, leaving the original String unchanged.

Whenever a String object is taken as an argument to a method, a reference is copied to the object, which remains in a single physical location and never moves. The lifetime of a local reference is only within a method, and parameters inform the method, not the method itself.

If you need to assemble strings in the for loop, be sure to use StringBuilder manually, otherwise redundant StringBuilder objects will be generated in the for loop. StringBuffer is a thread-safe implementation.

Regular expression

  • \\d represents a number, \\+ represents a common character +, and \\\\ represents a common backslash character (the first two parses are followed by the first two).
  • Vertical line says “or” space, such as “ABC”. Matches (” ((ABC) | (def)) + “)
  • [ABC] indicates any character containing a, B, and C. [^ ABC] indicates any character except a, B, and C
  • Matcher.find () can be called in a loop, each time finding matches an expression from the target string and ignores other extraneous characters, while the target string may match multiple expressions, centered on the expression rather than the target string. Matches () needs to match exactly. The level of groups is below here
  • In A(B(C))D, group 0 is ABCD, group 1 is BC, and group 2 is C
  • ? : matches but does not capture, for example (? | : ABC def | ig), can match the ABC def or ig but not included in the group

Text replacement, appendReplacement(StringBuffer sbuf, String replacement) performs progressive replacement, unlike replaceFirst and replaceAll, which replace with fixed strings, This allows custom programming to generate replacement.

String s = ”abd eaa“;
StringBuffer sbuf = new StringBuffer();
Patter p = Pattern.compile("[aeious]");
Matcher m = p.matcher(s):
while(m.find()) {
    m.appendReplacement(sbuf, m.group().toUpperCase());
}
m.appendTail(sbuf);
Copy the code

The enumeration

When you create an enum, the enum inherits from the enum class, and the compiler automatically adds some useful features. For example, it creates the toString() method so that you can easily display the name of an enum instance, the compiler creates ordinary() methods to indicate the order in which enum constants are declared, and static values() methods to indicate the order in which enum constants are declared. Produces an array of these constant values.

The following content is a little beyond the outline for the present, because the author is in the back of the writing and then come over…

public abstract class Enum<E extends Enum<E>>

enum Explore { HERE, THERE }

// compile auto generate
final class Explore extends java.lang.Enum {
    // that's why we use Explore.HERE
    public static final Explore HERE;
    public static final Explore THERE;
    public static final Explore[] values();
    public static Explore valueOf(java.lang.String);
    static {};
}
Copy the code

You can get all enum instances from the Class object, and non-enumeration Class calls will report an error.

enum Search { HITHER, YON }

public class UpcastEnum {
    public static void main(String[] args) {
        Search[] vals = Search.values();
        Enum e = Search.HITHER; // Upcast
        // e.values(); // No values() in Enum
        for(Enum en : e.getClass().getEnumConstants()) {
            System.out.println(en); // output: HITHER YON
        }
    }
}
Copy the code

So enum can’t inherit from other classes, but it’s ok to implement multiple inheritance of interfaces.

enum CartoonCharater implements Generator<CartoonCharater> { SPLAPPY, SPANKY, PUNCHY, SILLY, BOUNCY, NUTTY, BOB; private Random rand = new Random(47); public CartoonCharater next() { return values()[rand.nextInt(values().length)]; } } public class EnumImplementation { public static <T> void printNext(Generator<T> rg) { System.out.print(rg.next() + ". "); } public staic void main(String[] args) { CartoonCharater cc = CartoonCharater.BOB; for(int i = 0; i< 10; i++) { printNext(cc); }}}Copy the code

Java allows programmers to write methods for enum instances, thus giving each enum instance a different behavior. To implement constant-dependent methods, you need to define one or more abstract methods for the enum and then implement that abstract method for each enum instance. You can think of an enumeration class as a parent class, and an enumeration instance overrides or implements a parent class method. (I forgot about this feature earlier and did a similar thing by adding a Function member field to the enumeration, but inheritance is more appropriate.)

public enum ConstantSpecificMethod { DATE_TIME { String getinfo() { return DateFormat.getDateInstance().format(new Date)); } } abstract String getInfo(); public static void main(String[] args) { for(ConstantSpecificMethod csm: values()) { System.out.println(csm.getInfo()): }}}Copy the code

Java introduced EnumSet, which internally uses long to store ordinary() in Enum, with one member occupying one bit. It also provides EnumMap, which is internally implemented using arrays with subscripts of ordinary() in Enum.

annotations

Annotations can be used to generate descriptor files, or even new class definitions, and can help reduce the burden of writing boilerplate code. Whenever you create a descriptor class or interface that involves repetitive work, consider using annotations to simplify and automate the process.

Annotations combine metadata with source code files and use the Annotation API (not too arcane because it relies on Class objects) to build tools for their own annotations, rather than storing them in external documents. Annotations are really language-level concepts. Once constructed, it is protected by compile-time type checking, and the programmer has the power to inspect and manipulate source code and bytecode checking.

The definition of an annotation looks a lot like the definition of an interface; in fact, like any other Java interface, annotations will be compiled into a class file. Annotated elements look like interface methods, with the only difference that you can specify default values for them.