Java programming ideas

High Precision Numbers
Java provides two classes for high precision techniques: BigInteger and BigDecimal. Although they generally fall under the category of "wrapper classes", neither has a corresponding base type.
These two classes contain methods that provide operations similar to those that can be performed on primitive types. That is to say, operations that can be applied to int or float can also be applied to BigInteger
and BigDecimal. It's just that it must be implemented in the form of method calls instead of operators. Since this is a lot more complicated, the operation speed will be slower.
Accuracy traded for speed.
BigInteger supports arbitrary precision integers. That is, in arithmetic, integer values ​​of any size can be represented exactly without any loss of information.

BigDecimal supports fixed-point numbers of any precision. For example, it can be used for precise monetary calculations.


Auto-increment and decrement
For prefix-increment and prefix-decrement (such as ++a or --a), the operation is performed before the value is generated. For postfix increment and postfix decrement (such as a++ or a--),
the value is generated before the operation is performed.

public class Demo001 {
	public static void main(String[] args) {
		int i = 1;
		System.out.println(i);//1
		System.out.println(++i);//2
		System.out.println(i++);//2
		System.out.println(i);//3
		System.out.println(--i);//2
		System.out.println(i--);//2
		System.out.println(i);//1
		
	}
}



Most Java class libraries implement the equals() method so that they can be used to compare the contents of objects rather than their references.


When using logical operators, we encounter a kind of "short circuit" phenomenon. That is, once the value of the entire expression can be unambiguously determined, the remainder of the expression is not evaluated

part. Therefore, the later part of the entire logical expression may not be evaluated.

For booleans, bitwise operators have the same effect as logical operators, except they don't "short-circuit" halfway through.

return
if there is no return statement in a method that returns void. then there is an implicit return at the end of the method, so it
is not always necessary to have a return statement in a method. However, if a method declares that it will return something other than void,
then it must be ensured that every code path will return a value.
break and continue
In the body of any iteration statement, you can use break and continue to control the flow of the loop.
switch
The switch statement is a neat way to implement multiplexing. But it requires a selection factor and must be
an integer value like int or char. For example, if a string or floating point number is used as the selection factor, they will not
work in a switch statement. For non-integer types, a series of if statements must be used. The new feature enum in Java SE5 can help us reduce this limitation,
because enum can work in harmony with switch.

In a case statement, using single-quote characters also yields an integer value for comparison.

Although you can call one constructor with this, you cannot call two. Also, the constructor call must be placed at the very beginning,

Otherwise the compiler will report an error. The compiler prohibits calling the constructor from any method other than the constructor.

Re-discussion on composition and inheritance
In object-oriented programming, the most likely way to generate and use program code is to directly package data and methods into a class and make
objects of that class. Existing classes can also be used to develop new classes using composition techniques; inheritance techniques are actually less common. So while
we've emphasized inheritance many times in teaching OOP, that doesn't mean using it whenever possible. Instead, this technique should be used sparingly and
only in situations where you are confident that using the technique will actually work. One of the clearest ways to judge whether to use composition or inheritance is to ask
yourself if you need to upcast from the new class to the base class. If you must upcast, inheritance is necessary; but if you don't, you should
consider whether you need to upcast yourself.


There is a valid guideline when writing constructors: "Use the simplest possible way to bring an object to its normal state; avoid calling other
methods if you can". The only methods that are safe to call inside a constructor are final methods in the base class (also for private methods, which
are final). These methods cannot be overridden, so the above surprising problem does not arise.

The core reason to use an interface: To be able to upcast to multiple (multi-implementation) base types (and the resulting flexibility), the
second reason to use an interface is however the same as using an abstract base class: to prevent clients from The programmer creates an object of that class and makes sure that this is just an interface.


Interfaces and Factory
Interfaces are ways to achieve multiple inheritance, and the typical way to generate objects that conform to an interface is the factory method design pattern.
This is different from calling the constructor directly, we call the create method on the factory object, and the factory object generates an
object of an implementation of the interface.


HashSet, TreeSet, and LinkedHashSet are all Set types. The output is displayed in the Set, and each identical item is only saved once, but the
output also shows that different Sets implement different ways of storing elements. HashSet uses a fairly complex way to store elements,
. If storage order is important, you can use a TreeSet, which stores the results in ascending order of the comparison results, or a LinkedHashSet,
which stores objects in the order they were added.


The order in which keys and values ​​are kept in the Map is not their insertion order, because the HashMap implementation uses a very fast algorithm to control the order.
This example uses three basic flavors of Map: HashMap, TreeMap, and LinkedHashMap. Like HashSet, HashMap also provides the fastest
lookup technique and does not store its elements in any apparent order. TreeMap saves keys in ascending order of comparison results, while LinkedHashMap

The keys are saved in the order of insertion, while retaining the query speed of HashMap.

There is no regularity to the order of the HashSet output, this is because HashSet uses hashing for speed reasons.
HashSet maintains a different order than either TreeSet or LinkedHashSet because their implementations store elements differently.
TreeSet stores elements in a red-black tree data structure, while HashSet uses a hash function. LinkedHashSet
also uses hashing for query speed reasons, but it looks like it uses a linked list to maintain the insertion order of elements.
PriorityQueue
Integer, String, and Character work with PriorityQueue because these classes have natural ordering built in.
If you want to use your own class in PriorityQueue, you have to include extra functionality to produce natural ordering, or have to

Provide your own Comparator.


Java SE5 introduced a new interface called Iterable that contains an iterator()
method that produces an Iterator, and the Iterable interface is used by foreach to move through the sequence. So if you create any implementation of Iterable

class, you can use it in the foreach statement, the example is as follows:

public class IterableClass implements Iterable<String>{
	protected String[] words = ("And that is how" +
			"we know the Earth to be banana-shaped.").split(" ");
	@Override
	public Iterator<String> iterator() {
		// TODO Auto-generated method stub
		return new Iterator<String>(){
			private int index = 0;
			@Override
			public boolean hasNext() {
				return index < words.length;
			}

			@Override
			public String next() {
				return words[index++];
			}

			@Override
			public void remove() {
				
			}
			
		};
	}
	
	public static void main(String[] args) {
		for(String s : new IterableClass()){
			System.out.println(s + " ");
		}
	}

}
Containers cannot hold primitive types, but the automatic wrapping mechanism carefully performs two-way conversions from primitive types
to .
Various Queue and stack behaviors are supported by LinkedList.


Map is a design that associates objects (not numbers) with objects. HashMap is designed for fast access; while TreeMap keeps
the "keys" always sorted, so it is not as fast as HashMap. LinkedHashMap maintains the order in which elements were inserted, but also provides fast access through
hashing .


Set does not accept duplicate elements. HashSet provides the fastest query speed, while TreeSet keeps elements sorted. LinkedHashSet

Save elements in insertion order.

Explicitly creating a StringBuilder also allows you to specify its size in advance. If you already know how long the final string is,

That pre-specified StringBuilder size can avoid multiple reallocation of the buffer.


If you've used regular expressions in other languages, you'll immediately notice how Java handles backslashes \ differently. In other languages, \ means
"I want to insert a normal (literal) backslash into the regular expression, please don't give it any special meaning." In Java, \
means "I To insert a backslash in a regular expression, so the following characters have special meaning." For example, if you want to represent a digit,
the regular expression would be \d. If you wanted to insert a normal backslash, it would be \\\\. But things like newlines and tabs
only require single backslashes: \n\t.


The String class also comes with a very useful regular expression tool split() method, whose function is to "split the string from the
place where the regular expression matches"
String.split() There is also an overloaded version, which Allows you to limit the number of times the string is split.
The last regular expression tool that comes with the String class is "replace". You can replace only the first substring that matches the regular expression, or

Replace all matches.

All classes are dynamically loaded into the JVM when they are first used. The class loader first checks
whether the Class object of this class has been loaded. If not already loaded, the default class loader will look for the
.class file based on the class name. When the bytecode for this class is loaded, they are verified to ensure that it has not been corrupted
and does not contain bad Java code (this is one of the measures used in Java for security precautions)


Class literals
Java also provides Another way to generate a reference to a Class object is to use a class literal.
FancyToy.class: This is not only simpler, but also safer because it is checked at compile time
(so it doesn't need to be placed in a try block). And it eliminates the forName() method call, so it is also
more efficient.


Initialization is effectively as "lazy" as possible. As you can see from the creation of the reference to the initable, just using the
.class syntax to get a reference to the class does not cause initialization. However, in order to generate a Class reference, Class.forName()
is initialized immediately.
 If a static final value is a "compile-time constant", then the value can be read without initialization. However,
 simply making a field static or final is not enough to ensure this behavior.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325963690&siteId=291194637
Recommended