zoukankan      html  css  js  c++  java
  • Guava使用汇总

    一. ListsMaps 

    1. List<String> list = new ArrayList<String>();   => List<String> list = Lists.newArrayList();   & List<Integer> list = Lists.newArrayList(1, 2, 3);
    2. Map<String, Integer> map = new HashMap<String, Integer>(); => Map<String, Integer> list = Maps.newHashMap();

    二. ImmutableListImmutableMap 

     immutable对象(就是说状态不变)是个好东西. 它能让程序逻辑变得简单易懂, 而且减少出错的可能性.

    JDK目前不提供immutable集合. 瓜娃提供的最主要的immutable集合, 是ImmutableList, ImmutableSet和ImmutableMap. 

    怎么创建Immutable*?

    ImmutableList<Integer> list = ImmutableList.of(1, 2, 3);

    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("1", 1);
    map.put("2", 2);
    map.put("3", 3);

    假设你所有的不是事先知道的一些常量. 比如说, 你要从一个数据库里读出一些基本信息保存在内存里. 用of()就不好使了, 这时候, 可以用builder模式: 

    ImmutableMap.Builder<String, Integer> builder = ImmutableMap.builder();
    for (...) {
    builder.put(name, age);
    }
    ImmutableMap<String, Integer> map = builder.build();

    凡是可能的情况下, 给你的函数的返回类型用ImmutableList和ImmutableMap, 而不是它们实现的接口: List和Map. 比如: 

    Java代码
    1. ImmutableList<String> getNames();  
    2. ImmutableMap<String, Integer> getAgeMap();  


    而不是: 

    Java代码
      1. List<String> getNames();  
      2. Map<String, Integer> getAgeMap();  
  • 相关阅读:
    c# 判断网络是否连接
    有关TSQL的10个好习惯
    相同文件只能一个进程读取
    我的单元测试方案
    又用了一把VBA
    深入理解字符串和字节数组转换
    如何清除应用程序承载 WebBrowser 控件时缓存
    VB也绿色
    ASP.Net网站开发的单元测试方案
    Nunit使用心得
  • 原文地址:https://www.cnblogs.com/binnzhao/p/6394097.html
Copyright © 2011-2022 走看看