Use interface references to Collections

http://www.javapractices.com/topic/TopicAction.do?Id=26


In general, references to objects should be as generic as possible. The user of such a reference will be protected from possible changes to the underlying implementation class. The ripple effects of such a change are limited to the single line of code which creates the object, and will not propagate any further.

In the case of collections, this means habitually referring to collection objects using ListMapSetQueue, and Deque interface references.

Note as well that all of these except Map can be referred to using the even more generic Collection.

Example 

import java.util.*;

public class Nucleus {

  public static void main (String... arguments) {
    Nucleus lithium = new Nucleus (3,4);
    //note the generic Map reference is used here, not LinkedHashMap
    Map<String, Integer> quarks = lithium.getQuarkSummary();
    log("Number of up quarks in lithium nucleus: " + quarks.get("Up"));
    log("Number of down quarks in lithium nucleus: " + quarks.get("Down"));
  }

  public Nucleus(int aNumProtons, int aNumNeutrons) {
    fNumProtons = aNumProtons;
    fNumNeutrons = aNumNeutrons;
  }

  /** Note get method is final. */
  public final int getNumProtons() {
     return fNumProtons;
  }

  /** Note get method is final. */
  public final int getNumNeutrons() {
     return fNumNeutrons;
  }

  /**
  * This method returns a Map which summarizes how many quarks of each
  * flavour are in the nucleus.
  *
  * @return a generic Map reference, instead of a LinkedHashMap; the
  * user will be protected from the detail of what implementation of Map
  * has been selected here.
  */
  public final Map<String, Integer> getQuarkSummary() {
    LinkedHashMap<String, Integer> result = new LinkedHashMap<>();
    int numUp =
      fNumProtons * fUP_QUARKS_PER_PROTON +
      fNumNeutrons * fUP_QUARKS_PER_NEUTRON
    ;
    int numDown =
      fNumProtons * fDOWN_QUARKS_PER_PROTON +
      fNumNeutrons * fDOWN_QUARKS_PER_NEUTRON
    ;
    //this makes use of auto-boxing of ints into Integers:
    result.put("Up", numUp);
    result.put("Down", numDown);
    return result;
  }

  //PRIVATE 
  private final int fNumProtons;
  private final int fNumNeutrons;

  private static final int fUP_QUARKS_PER_PROTON = 2;
  private static final int fDOWN_QUARKS_PER_PROTON = 1;

  private static final int fUP_QUARKS_PER_NEUTRON = 1;
  private static final int fDOWN_QUARKS_PER_NEUTRON = 2;

  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值