zoukankan      html  css  js  c++  java
  • Effective Java

    Effective Java: Programming Language Guide

    • Item 1: Consider providing static factory methods instead of constructor.

    Advantage: have a name, no new operator everytime, return any subtype of iteself.   Consider pattern: Singleton and Factory method (with many different ways to implement: Creator by inheritance, parameterized method, Template, Class::forName( … ). newInstance() in java). In java, all objects are reference, but value. so use new operator as less as possible. All assumption based on reference ( clone, equal, hashCode, Comparable.compareTos)

    • Items 2: Enforce the singleton property with a private constructor. Singleton Pattern.
    • Items 3: Enforece non-instantiability with a private constructor.
    • Item 4: Avoid creating duplicate objects. Not use new operator much. Reference to object is kept track by JVM.
    • Item 5: Eliminate obsolete object reference. Let reference of object null in order to let gc do its work.
    • Item 6: Avoid finalizer instead of providing an explicit termination method in tryàcatchàfinally block. Finalizer of superclass must be invoked in your finalizer.
    • Item 7: Obey the general contract when overriding equals of Object. Although object is a concrete class, it is designed primarily for extension. All of its non-final method(equals, hashcode, toString, clone, and finalize) have explicit general contracts because they are designed to be overiden. It is the responsibility of any class overiding these methods to obey their general contracts; failure to do so will prevent other classes that depend on these contracts from functioning properly in conjunction with the class. Also including interface: Comparable. compareTo.
    •   1 /*
        2  * Licensed to the Apache Software Foundation (ASF) under one or more
        3  * contributor license agreements.  See the NOTICE file distributed with
        4  * this work for additional information regarding copyright ownership.
        5  * The ASF licenses this file to You under the Apache License, Version 2.0
        6  * (the "License"); you may not use this file except in compliance with
        7  * the License.  You may obtain a copy of the License at
        8  *
        9  *     http://www.apache.org/licenses/LICENSE-2.0
       10  *
       11  * Unless required by applicable law or agreed to in writing, software
       12  * distributed under the License is distributed on an "AS IS" BASIS,
       13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       14  * See the License for the specific language governing permissions and
       15  * limitations under the License.
       16  */
       17 /*
       18  * Copyright (C) 2008 The Android Open Source Project
       19  *
       20  * Licensed under the Apache License, Version 2.0 (the "License");
       21  * you may not use this file except in compliance with the License.
       22  * You may obtain a copy of the License at
       23  *
       24  *      http://www.apache.org/licenses/LICENSE-2.0
       25  *
       26  * Unless required by applicable law or agreed to in writing, software
       27  * distributed under the License is distributed on an "AS IS" BASIS,
       28  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       29  * See the License for the specific language governing permissions and
       30  * limitations under the License.
       31  */
       32 
       33 package java.lang;
       34 
       35 /**
       36  * The root class of the Java class hierarchy. All non-primitive types
       37  * (including arrays) inherit either directly or indirectly from this class.
       38  *
       39  * <a name="writing_equals"><h4>Writing a correct {@code equals} method</h4></a>
       40  * <p>Follow this style to write a canonical {@code equals} method:
       41  * <pre>
       42  *   // Use @Override to avoid accidental overloading.
       43  *   &#x0040;Override public boolean equals(Object o) {
       44  *     // Return true if the objects are identical.
       45  *     // (This is just an optimization, not required for correctness.)
       46  *     if (this == o) {
       47  *       return true;
       48  *     }
       49  *
       50  *     // Return false if the other object has the wrong type.
       51  *     // This type may be an interface depending on the interface's specification.
       52  *     if (!(o instanceof MyType)) {
       53  *       return false;
       54  *     }
       55  *
       56  *     // Cast to the appropriate type.
       57  *     // This will succeed because of the instanceof, and lets us access private fields.
       58  *     MyType lhs = (MyType) o;
       59  *
       60  *     // Check each field. Primitive fields, reference fields, and nullable reference
       61  *     // fields are all treated differently.
       62  *     return primitiveField == lhs.primitiveField &amp;&amp;
       63  *             referenceField.equals(lhs.referenceField) &amp;&amp;
       64  *             (nullableField == null ? lhs.nullableField == null
       65  *                                    : nullableField.equals(lhs.nullableField));
       66  *   }
       67  * </pre>
       68  * <p>If you override {@code equals}, you should also override {@code hashCode}: equal
       69  * instances must have equal hash codes.
       70  *
       71  * <p>See <i>Effective Java</i> item 8 for much more detail and clarification.
       72  *
       73  * <a name="writing_hashCode"><h4>Writing a correct {@code hashCode} method</h4></a>
       74  * <p>Follow this style to write a canonical {@code hashCode} method:
       75  * <pre>
       76  *   &#x0040;Override public int hashCode() {
       77  *     // Start with a non-zero constant.
       78  *     int result = 17;
       79  *
       80  *     // Include a hash for each field.
       81  *     result = 31 * result + (booleanField ? 1 : 0);
       82  *
       83  *     result = 31 * result + byteField;
       84  *     result = 31 * result + charField;
       85  *     result = 31 * result + shortField;
       86  *     result = 31 * result + intField;
       87  *
       88  *     result = 31 * result + (int) (longField ^ (longField >>> 32));
       89  *
       90  *     result = 31 * result + Float.floatToIntBits(floatField);
       91  *
       92  *     long doubleFieldBits = Double.doubleToLongBits(doubleField);
       93  *     result = 31 * result + (int) (doubleFieldBits ^ (doubleFieldBits >>> 32));
       94  *
       95  *     result = 31 * result + Arrays.hashCode(arrayField);
       96  *
       97  *     result = 31 * result + referenceField.hashCode();
       98  *     result = 31 * result +
       99  *         (nullableReferenceField == null ? 0
      100  *                                         : nullableReferenceField.hashCode());
      101  *
      102  *     return result;
      103  *   }
      104  * </pre>
      105  *
      106  * <p>If you don't intend your type to be used as a hash key, don't simply rely on the default
      107  * {@code hashCode} implementation, because that silently and non-obviously breaks any future
      108  * code that does use your type as a hash key. You should throw instead:
      109  * <pre>
      110  *   &#x0040;Override public int hashCode() {
      111  *     throw new UnsupportedOperationException();
      112  *   }
      113  * </pre>
      114  *
      115  * <p>See <i>Effective Java</i> item 9 for much more detail and clarification.
      116  *
      117  * <a name="writing_toString"><h4>Writing a useful {@code toString} method</h4></a>
      118  * <p>For debugging convenience, it's common to override {@code toString} in this style:
      119  * <pre>
      120  *   &#x0040;Override public String toString() {
      121  *     return getClass().getName() + "[" +
      122  *         "primitiveField=" + primitiveField + ", " +
      123  *         "referenceField=" + referenceField + ", " +
      124  *         "arrayField=" + Arrays.toString(arrayField) + "]";
      125  *   }
      126  * </pre>
      127  * <p>The set of fields to include is generally the same as those that would be tested
      128  * in your {@code equals} implementation.
      129  * <p>See <i>Effective Java</i> item 10 for much more detail and clarification.
      130  */
      131 public class Object {
      132     /**
      133      * Constructs a new instance of {@code Object}.
      134      */
      135     public Object() {
      136     }
      137 
      138     /**
      139      * Creates and returns a copy of this {@code Object}. The default
      140      * implementation returns a so-called "shallow" copy: It creates a new
      141      * instance of the same class and then copies the field values (including
      142      * object references) from this instance to the new instance. A "deep" copy,
      143      * in contrast, would also recursively clone nested objects. A subclass that
      144      * needs to implement this kind of cloning should call {@code super.clone()}
      145      * to create the new instance and then create deep copies of the nested,
      146      * mutable objects.
      147      *
      148      * @return a copy of this object.
      149      * @throws CloneNotSupportedException
      150      *             if this object's class does not implement the {@code
      151      *             Cloneable} interface.
      152      */
      153     protected Object clone() throws CloneNotSupportedException {
      154         if (!(this instanceof Cloneable)) {
      155             throw new CloneNotSupportedException("Class doesn't implement Cloneable");
      156         }
      157 
      158         return internalClone((Cloneable) this);
      159     }
      160 
      161     /*
      162      * Native helper method for cloning.
      163      */
      164     private native Object internalClone(Cloneable o);
      165 
      166     /**
      167      * Compares this instance with the specified object and indicates if they
      168      * are equal. In order to be equal, {@code o} must represent the same object
      169      * as this instance using a class-specific comparison. The general contract
      170      * is that this comparison should be reflexive, symmetric, and transitive.
      171      * Also, no object reference other than null is equal to null.
      172      *
      173      * <p>The default implementation returns {@code true} only if {@code this ==
      174      * o}. See <a href="{@docRoot}reference/java/lang/Object.html#writing_equals">Writing a correct
      175      * {@code equals} method</a>
      176      * if you intend implementing your own {@code equals} method.
      177      *
      178      * <p>The general contract for the {@code equals} and {@link
      179      * #hashCode()} methods is that if {@code equals} returns {@code true} for
      180      * any two objects, then {@code hashCode()} must return the same value for
      181      * these objects. This means that subclasses of {@code Object} usually
      182      * override either both methods or neither of them.
      183      *
      184      * @param o
      185      *            the object to compare this instance with.
      186      * @return {@code true} if the specified object is equal to this {@code
      187      *         Object}; {@code false} otherwise.
      188      * @see #hashCode
      189      */
      190     public boolean equals(Object o) {
      191         return this == o;
      192     }
      193 
      194     /**
      195      * Invoked when the garbage collector has detected that this instance is no longer reachable.
      196      * The default implementation does nothing, but this method can be overridden to free resources.
      197      *
      198      * <p>Note that objects that override {@code finalize} are significantly more expensive than
      199      * objects that don't. Finalizers may be run a long time after the object is no longer
      200      * reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup.
      201      * Note also that finalizers are run on a single VM-wide finalizer thread,
      202      * so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary
      203      * for a class that has a native peer and needs to call a native method to destroy that peer.
      204      * Even then, it's better to provide an explicit {@code close} method (and implement
      205      * {@link java.io.Closeable}), and insist that callers manually dispose of instances. This
      206      * works well for something like files, but less well for something like a {@code BigInteger}
      207      * where typical calling code would have to deal with lots of temporaries. Unfortunately,
      208      * code that creates lots of temporaries is the worst kind of code from the point of view of
      209      * the single finalizer thread.
      210      *
      211      * <p>If you <i>must</i> use finalizers, consider at least providing your own
      212      * {@link java.lang.ref.ReferenceQueue} and having your own thread process that queue.
      213      *
      214      * <p>Unlike constructors, finalizers are not automatically chained. You are responsible for
      215      * calling {@code super.finalize()} yourself.
      216      *
      217      * <p>Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer
      218      * thread.
      219      *
      220      * See <i>Effective Java</i> Item 7, "Avoid finalizers" for more.
      221      */
      222     @FindBugsSuppressWarnings("FI_EMPTY")
      223     protected void finalize() throws Throwable {
      224     }
      225 
      226     /**
      227      * Returns the unique instance of {@link Class} that represents this
      228      * object's class. Note that {@code getClass()} is a special case in that it
      229      * actually returns {@code Class<? extends Foo>} where {@code Foo} is the
      230      * erasure of the type of the expression {@code getClass()} was called upon.
      231      * <p>
      232      * As an example, the following code actually compiles, although one might
      233      * think it shouldn't:
      234      * <p>
      235      * <pre>{@code
      236      *   List<Integer> l = new ArrayList<Integer>();
      237      *   Class<? extends List> c = l.getClass();}</pre>
      238      *
      239      * @return this object's {@code Class} instance.
      240      */
      241     public final native Class<?> getClass();
      242 
      243     /**
      244      * Returns an integer hash code for this object. By contract, any two
      245      * objects for which {@link #equals} returns {@code true} must return
      246      * the same hash code value. This means that subclasses of {@code Object}
      247      * usually override both methods or neither method.
      248      *
      249      * <p>Note that hash values must not change over time unless information used in equals
      250      * comparisons also changes.
      251      *
      252      * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_hashCode">Writing a correct
      253      * {@code hashCode} method</a>
      254      * if you intend implementing your own {@code hashCode} method.
      255      *
      256      * @return this object's hash code.
      257      * @see #equals
      258      */
      259     public native int hashCode();
      260 
      261     /**
      262      * Causes a thread which is waiting on this object's monitor (by means of
      263      * calling one of the {@code wait()} methods) to be woken up. If more than
      264      * one thread is waiting, one of them is chosen at the discretion of the
      265      * VM. The chosen thread will not run immediately. The thread
      266      * that called {@code notify()} has to release the object's monitor first.
      267      * Also, the chosen thread still has to compete against other threads that
      268      * try to synchronize on the same object.
      269      * <p>
      270      * This method can only be invoked by a thread which owns this object's
      271      * monitor. A thread becomes owner of an object's monitor
      272      * </p>
      273      * <ul>
      274      * <li>by executing a synchronized method of that object;</li>
      275      * <li>by executing the body of a {@code synchronized} statement that
      276      * synchronizes on the object;</li>
      277      * <li>by executing a synchronized static method if the object is of type
      278      * {@code Class}.</li>
      279      * </ul>
      280      *
      281      * @see #notifyAll
      282      * @see #wait()
      283      * @see #wait(long)
      284      * @see #wait(long,int)
      285      * @see java.lang.Thread
      286      */
      287     public final native void notify();
      288 
      289     /**
      290      * Causes all threads which are waiting on this object's monitor (by means
      291      * of calling one of the {@code wait()} methods) to be woken up. The threads
      292      * will not run immediately. The thread that called {@code notify()} has to
      293      * release the object's monitor first. Also, the threads still have to
      294      * compete against other threads that try to synchronize on the same object.
      295      * <p>
      296      * This method can only be invoked by a thread which owns this object's
      297      * monitor. A thread becomes owner of an object's monitor
      298      * </p>
      299      * <ul>
      300      * <li>by executing a synchronized method of that object;</li>
      301      * <li>by executing the body of a {@code synchronized} statement that
      302      * synchronizes on the object;</li>
      303      * <li>by executing a synchronized static method if the object is of type
      304      * {@code Class}.</li>
      305      * </ul>
      306      *
      307      * @throws IllegalMonitorStateException
      308      *             if the thread calling this method is not the owner of this
      309      *             object's monitor.
      310      * @see #notify
      311      * @see #wait()
      312      * @see #wait(long)
      313      * @see #wait(long,int)
      314      * @see java.lang.Thread
      315      */
      316     public final native void notifyAll();
      317 
      318     /**
      319      * Returns a string containing a concise, human-readable description of this
      320      * object. Subclasses are encouraged to override this method and provide an
      321      * implementation that takes into account the object's type and data. The
      322      * default implementation is equivalent to the following expression:
      323      * <pre>
      324      *   getClass().getName() + '@' + Integer.toHexString(hashCode())</pre>
      325      * <p>See <a href="{@docRoot}reference/java/lang/Object.html#writing_toString">Writing a useful
      326      * {@code toString} method</a>
      327      * if you intend implementing your own {@code toString} method.
      328      *
      329      * @return a printable representation of this object.
      330      */
      331     public String toString() {
      332         return getClass().getName() + '@' + Integer.toHexString(hashCode());
      333     }
      334 
      335     /**
      336      * Causes the calling thread to wait until another thread calls the {@code
      337      * notify()} or {@code notifyAll()} method of this object. This method can
      338      * only be invoked by a thread which owns this object's monitor; see
      339      * {@link #notify()} on how a thread can become the owner of a monitor.
      340      * <p>
      341      * A waiting thread can be sent {@code interrupt()} to cause it to
      342      * prematurely stop waiting, so {@code wait} should be called in a loop to
      343      * check that the condition that has been waited for has been met before
      344      * continuing.
      345      * </p>
      346      * <p>
      347      * While the thread waits, it gives up ownership of this object's monitor.
      348      * When it is notified (or interrupted), it re-acquires the monitor before
      349      * it starts running.
      350      * </p>
      351      *
      352      * @throws IllegalMonitorStateException
      353      *             if the thread calling this method is not the owner of this
      354      *             object's monitor.
      355      * @throws InterruptedException
      356      *             if another thread interrupts this thread while it is waiting.
      357      * @see #notify
      358      * @see #notifyAll
      359      * @see #wait(long)
      360      * @see #wait(long,int)
      361      * @see java.lang.Thread
      362      */
      363     public final void wait() throws InterruptedException {
      364         wait(0 ,0);
      365     }
      366 
      367     /**
      368      * Causes the calling thread to wait until another thread calls the {@code
      369      * notify()} or {@code notifyAll()} method of this object or until the
      370      * specified timeout expires. This method can only be invoked by a thread
      371      * which owns this object's monitor; see {@link #notify()} on how a thread
      372      * can become the owner of a monitor.
      373      * <p>
      374      * A waiting thread can be sent {@code interrupt()} to cause it to
      375      * prematurely stop waiting, so {@code wait} should be called in a loop to
      376      * check that the condition that has been waited for has been met before
      377      * continuing.
      378      * </p>
      379      * <p>
      380      * While the thread waits, it gives up ownership of this object's monitor.
      381      * When it is notified (or interrupted), it re-acquires the monitor before
      382      * it starts running.
      383      * </p>
      384      *
      385      * @param millis
      386      *            the maximum time to wait in milliseconds.
      387      * @throws IllegalArgumentException
      388      *             if {@code millis < 0}.
      389      * @throws IllegalMonitorStateException
      390      *             if the thread calling this method is not the owner of this
      391      *             object's monitor.
      392      * @throws InterruptedException
      393      *             if another thread interrupts this thread while it is waiting.
      394      * @see #notify
      395      * @see #notifyAll
      396      * @see #wait()
      397      * @see #wait(long,int)
      398      * @see java.lang.Thread
      399      */
      400     public final void wait(long millis) throws InterruptedException {
      401         wait(millis, 0);
      402     }
      403 
      404     /**
      405      * Causes the calling thread to wait until another thread calls the {@code
      406      * notify()} or {@code notifyAll()} method of this object or until the
      407      * specified timeout expires. This method can only be invoked by a thread
      408      * that owns this object's monitor; see {@link #notify()} on how a thread
      409      * can become the owner of a monitor.
      410      * <p>
      411      * A waiting thread can be sent {@code interrupt()} to cause it to
      412      * prematurely stop waiting, so {@code wait} should be called in a loop to
      413      * check that the condition that has been waited for has been met before
      414      * continuing.
      415      * </p>
      416      * <p>
      417      * While the thread waits, it gives up ownership of this object's monitor.
      418      * When it is notified (or interrupted), it re-acquires the monitor before
      419      * it starts running.
      420      * </p>
      421      *
      422      * @param millis
      423      *            the maximum time to wait in milliseconds.
      424      * @param nanos
      425      *            the fraction of a millisecond to wait, specified in
      426      *            nanoseconds.
      427      * @throws IllegalArgumentException
      428      *             if {@code millis < 0}, {@code nanos < 0} or {@code nanos >
      429      *             999999}.
      430      * @throws IllegalMonitorStateException
      431      *             if the thread calling this method is not the owner of this
      432      *             object's monitor.
      433      * @throws InterruptedException
      434      *             if another thread interrupts this thread while it is waiting.
      435      * @see #notify
      436      * @see #notifyAll
      437      * @see #wait()
      438      * @see #wait(long,int)
      439      * @see java.lang.Thread
      440      */
      441     public final native void wait(long millis, int nanos) throws InterruptedException;
      442 }
      View Code
    • Item 8: Always overide hashCode when you orveride equals.
    • Item 9: Always overide toString.
    • Item 10: Overide clone judiciously(wisely).
    •  1 package java.lang;
       2 
       3 
       4 /**
       5  * This (empty) interface must be implemented by all classes that wish to
       6  * support cloning. The implementation of {@code clone()} in {@code Object}
       7  * checks if the object being cloned implements this interface and throws
       8  * {@code CloneNotSupportedException} if it does not.
       9  *
      10  * @see Object#clone
      11  * @see CloneNotSupportedException
      12  */
      13 public interface Cloneable {
      14     // Marker interface
      15 }
      View Code
    • Item 11: Consider implementing Comparable.
    •  1 public interface Comparable<T> {
       2 
       3     /**
       4      * Compares this object to the specified object to determine their relative
       5      * order.
       6      *
       7      * @param another
       8      *            the object to compare to this instance.
       9      * @return a negative integer if this instance is less than {@code another};
      10      *         a positive integer if this instance is greater than
      11      *         {@code another}; 0 if this instance has the same order as
      12      *         {@code another}.
      13      * @throws ClassCastException
      14      *             if {@code another} cannot be converted into something
      15      *             comparable to {@code this} instance.
      16      */
      17     int compareTo(T another);
      18 }
      View Code
    • Item 12: Minimize the accessibility of classes and member.
    • Item 13: Favor immutability
    • Item 14: Favor composition over inheritance.
    • Item 15: Design and document for inheritance or else prohibit it.
    • Item 16: Prefer interface to abstract classes
    • Item 17: Use interface only to defint types.
    • Item 18: Favor static member classes over non-static.
    • Item 19: Replace structures with classes
    • Item 20: Replace unions with class hierachies
    • Item 21: Replace enum constructs with classes.
    • Item 22: Replace function pointer with classes and interfaces.
    • Item 23: Check parameters for validity
    • Item 24: Make defensive copies when needed.
    • Item 25: Desgin method signatures carefully
    • Item 26: Use overloading wisely
    • Item 27: Return zero-length arrays, not nulls
    • Item 28: Write doc comments for all exposed API elements.
    • Item 29: Minimize the scope of local variables.
    • Item 30: Know and use the libraries
    • Item 31: Avoid float and double if exact answers are required
    • Item 32: Avoid strings where others types are more appropirate.
    • Item 33: Beware the performance of string concatenation
    • Item 34: Refer to objects by their interfaces.
    • Item 35: Pefer interfaces to reflection
    • Item 36: Use native methods judiciously
    • Item 37: Optimize judiciously
    • Item 38: Adhere to generally accepted naming conventions
    • Item 39: Use exceptions only for exceptional conditions.
    • Item 40: Use checked exceptions for recoverable conditions and run-time exceptions for programming errors.
    • Item 41: Avoid unnecessary use of checked exceptions.
    • Item 42: Favor the use of standard exceptions
    • Item 43: Throw exceptions appropriate to the abstraction
    • Item 44: Document all exceptions thrown by each method
    • Item 45: Include failur-capture information in detail messages
    • Item 47: Don’t ignore exceptions
    • Item 48: Synchronize access to shared mutable data.
    • Item 49: Avoid excessive synchronization
    • Item 50: Never invoke wait outside a loop.
    • Item 51: Don’t depend on the thread scheduler.
    • Item 52: Document thread safely
    • Item 53: Avoid thread groups
    • Item 54: Implement Serializable judiciously
    • Item 55: Consider using a custom serialized form
    • Item 56: Write readObject methods defensively
    • Item 57: Provide a readResovle method when necessary
  • 相关阅读:
    delphi消息发送字符串
    Delphi2007 在Win10 下运行报错 Assertion failure
    python 定时器
    python 直接赋值 深浅拷贝
    python 闭包
    python 对象
    c++ sizeof和strlen
    c++入门笔记(一)
    python实现四种排序逻辑与代码
    webrtc autotest
  • 原文地址:https://www.cnblogs.com/iiiDragon/p/3271866.html
Copyright © 2011-2022 走看看