Write high-quality code: 151 recommendations for improving Java programs--[78~92]hashmap hashcode should avoid conflict multithreading using vectors or hashtable
Vector is a multithreaded version of ArrayList, and Hashtable is a multithreaded version of HashMap.
Non-stable Sort recommended list
Sort the set of changes
- Set=new TreeSet
- Using TreeSet is to automate sorting, even if the modification is automatic, and since it cannot be implemented, use list instead and use the Collections.sort () method to sort the list
Import java.util.arraylist;import Java.util.sortedset;import Java.util.treeset;public class Client69 {public St atic void Main (string[] args) {sortedset<person> set = new treeset<person> (); Height 180CM set.add (new person (180)); Height 175CM set.add (new Person (175)); Set.first (). SetHeight (185); Set=new treeset<person> (New arraylist<person> (set)); for (person P:set) {System.out.println ("Height:" + p.getheight ()); }} static class person implements Comparable<person> {//height private int height; public person (int _height) {height = _height; } public int getheight () {return height; } public void setheight (int height) {this.height = height; }//Sort by height @Override public int compareTo (person o) {return height-o.height; } }}
Enumeration constants are recommended in the project instead of interface constants or class constants
enum Season { Spring, Summer, Autumn, Winter; public static Season getComfortableSeason(){ return Spring; } }
Using constructors to assist in describing enumeration items
enum Role { Admin("管理员", new LifeTime(), new Scope()), User("普通用户", new LifeTime(), new Scope()); private String name; private LifeTime lifeTime; private Scope scope; /* setter和getter方法略 */ Role(String _name, LifeTime _lifeTime, Scope _scope) { name = _name; lifeTime = _lifeTime; scope = _scope; }}class LifeTime {}class Scope {}
Name: Represents the Chinese name of the role
LifeTime: Represents the life cycle of the role, that is, how long the role fails
Scope: The permission range of the role represented
Be careful that the null pointer exception that is brought by the switch adds Assertionerror error in the default code block of switch and must be verified before using valueof
Enumeration. VALUEOF (name)
No match found for the specified value error:
Exception in thread "main" java.lang.IllegalArgumentException: No enum ... at java.lang.Enum.valueOf(Unknown Source)
Two ways to avoid it:
(1), using Try......catch to catch the exception
try{ 枚举.valueOf(name) }catch(Exception e){ e.printStackTrace(); System.out.println("无相关枚举项"); }
(2), Extended enumeration class
enum Season { Spring, Summer, Autumn, Winter; // 是否包含指定的枚举项 public static boolean isContains(String name) { // 所有的枚举值 Season[] season = values(); for (Season s : season) { if (s.name().equals(name)) { return true; } } return false; } }
Using enumerations to implement factory method patterns is more concise
Enumerating non-static methods to implement a factory method pattern
enum CarFactory { // 定义生产类能生产汽车的类型 FordCar, BuickCar; // 生产汽车 public Car create() { switch (this) { case FordCar: return new FordCar(); case BuickCar: return new BuickCar(); default: throw new AssertionError("无效参数"); } }}
Generating products through an abstract approach
enum CarFactory { // 定义生产类能生产汽车的类型 FordCar{ public Car create(){ return new FordCar(); } }, BuickCar{ public Car create(){ return new BuickCar(); } }; //抽象生产方法 public abstract Car create();}
There are three advantages to using the factory method pattern of an enumeration type:
- Avoid the occurrence of false calls: the production method in the General factory method mode (i.e. the Createcar method), can receive three types of parameters: type parameters (such as our example), the string parameter (in the production method to determine what product the string parameter is required to produce), the int parameter ( Judging by the int value of what type of product you need to produce, these three parameters are broad data types that are prone to errors (such as boundary problems, null value problems), and the compiler will not alert you if such errors occur.
- Good performance, simple to use: enumeration type of calculation based on the calculation of int type, this is the most basic operation, of course, performance will be quick, as for the use of convenience, pay attention to the client's call.
- Reduced inter-class coupling: Regardless of whether the production method receives parameters of class, String, or int, it becomes a burden on the client class, which is not required by the client, but because the factory method restrictions must be entered, such as the class parameter, for the client Main method, He needs to pass a Fordcar.class parameter in order to produce a Ford car, in addition to passing parameters in the Create method, the business class does not need to change the implementation class of car. This is a serious violation of the Dimitri principle (law of Demeter, Lod), which is the least knowledge principle: An object should have the least understanding of other objects.
There is no such problem with the factory method of the enumeration type, it only needs to rely on the factory class.
The number of enumerated items is limited to less than 64
To better use enumerations, Java provides two enumeration collections: Enumset and Enummap, which use a simple method, enumset that their elements must be an enumeration of an enumeration, enummap that the key value must be an enumeration of an enumeration, Because the number of instances of enumerated types is fixed and limited, enumset and enummap are relatively more efficient than other set and map.
When the number of enumerated items is less than or equal to 64 o'clock, a Regularenumset instance object is created, and a Jumboenumset instance object is created when it is greater than 64.
Do not exceed 64 for the number of enumerated items, otherwise it is recommended to split.
import Java.util.enumset;public class Enumsettest {///normal enum, number equals const{a,b,c,d,e,f,g,h,i,j,k,l, M,n,o,p,q,r,s,t,u,v,w,x,y,z, Aa,bb,cc,dd,ee,ff,gg,hh,ii,jj,kk,ll,mm,nn,oo,pp,qq,rr,ss,tt,uu,vv,ww,xx,yy,zz, AAA,BBB,CCC,DDD,EEE,FFF,GGG,HHH,III,JJJ,KKK,LLL}//Large enumeration, more than the number of enum largeconst{a,b,c,d,e,f,g,h,i,j,k,l,m, N,o,p,q,r,s,t,u,v,w,x,y,z, Aa,bb,cc,dd,ee,ff,gg,hh,ii,jj,kk,ll,mm,nn,oo,pp,qq,rr,ss,tt,uu,vv,ww,xx,yy,zz, AA AA,BBBB,CCCC,DDDD,EEEE,FFFF,GGGG,HHHH,IIII,JJJJ,KKKK,LLLL,MMMM} public static void Main (string[] args) {Enu Mset<const> cs = Enumset.allof (const.class); enumset<largeconst> LCS = Enumset.allof (Largeconst.class); Prints out the enumerator number System.out.println ("Const enumeration Number:" +cs.size ()); System.out.println ("Largeconst enumeration number:" +lcs.size ()); Output two Enumset class System.out.println (Cs.getclass ()); System.out.println (Lcs.getclass ()); }}
AllOf Call noneof
public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) { //生成一个空EnumSet EnumSet<E> result = noneOf(elementType); //加入所有的枚举项 result.addAll(); return result; }
public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) { //获得所有的枚举项 Enum[] universe = getUniverse(elementType); if (universe == null) throw new ClassCastException(elementType + " not an enum"); //枚举数量小于等于64 if (universe.length <= 64) return new RegularEnumSet<>(elementType, universe); else //枚举数量大于64 return new JumboEnumSet<>(elementType, universe); }
Note the difference between different versions of @override
interface Foo { public void doSomething();}class FooImpl implements Foo{ @Override public void doSomething() { }}
This code compiles on the Java1.6 version no problem, although the DoSomething method only implements the interface definition, is strictly not overwrite, but @override appears here can reduce the error in the code.
If this code is compiled on the Java1.5 version, an error may occur: The method dosomething () of type Fooimpl must override a superclass method.
Java1.5 version of @override is strict adherence to the definition of overwrite: The subclass method and the parent class method must have the same method name, output parameters, output parameters (allow subclasses to shrink), access permissions (allow subclasses to enlarge), the parent class must be a class, cannot be an interface, otherwise it can not be considered as overwrite. And this opens up a lot in the Java1.6, the method that implements the interface can also add @override annotation, can avoid careless cause the method name and interface inconsistency of circumstance occurrence.
Java1.6 version of the program is ported to the 1.5 version of the environment, you need to remove the implementation interface methods on the @override annotations.
Write high-quality code: 151 recommendations for improving Java programs--[78~92]