zoukankan      html  css  js  c++  java
  • Why use interface type to declare a collectio

    The following program prints out all distinct words in its argument list. Two versions of this program are provided. The first uses JDK 8 aggregate operations. The second uses the for-each construct.

    Using JDK 8 Aggregate Operations:

    import java.util.*;
    import java.util.stream.*;

    public class FindDups {
    public static void main(String[] args) {
    Set<String> distinctWords = Arrays.asList(args).stream()
    .collect(Collectors.toSet());
    System.out.println(distinctWords.size()+
    " distinct words: " +
    distinctWords);
    }
    }
    Using the for-each Construct:

    import java.util.*;

    public class FindDups {
    public static void main(String[] args) {
    Set<String> s = new HashSet<String>();
    for (String a : args)
    s.add(a);
    System.out.println(s.size() + " distinct words: " + s);
    }
    }

    Now run either version of the program.

    java FindDups i came i saw i left
    The following output is produced:

    4 distinct words: [left, came, saw, i]
    Note that the code always refers to the Collection by its interface type (Set) rather than by its implementation type. This is a strongly recommended programming practice because it gives you the flexibility to change implementations merely by changing the constructor. If either of the variables used to store a collection or the parameters used to pass it around are declared to be of the Collection's implementation type rather than its interface type, all such variables and parameters must be changed in order to change its implementation type.

    Furthermore, there's no guarantee that the resulting program will work. If the program uses any nonstandard operations present in the original implementation type but not in the new one, the program will fail. Referring to collections only by their interface prevents you from using any nonstandard operations.

  • 相关阅读:
    laydate日期插件弹出闪退和多次闪退问题解决
    IconFont 图标的3种引用方式
    jquery操作select下拉框的多种方法(选中,取值,赋值等)
    jquery获取select选中项 自定义属性的值
    Centos查看端口占用、开启端口
    IaaS,PaaS,SaaS 的区别
    IOS手机使用Fiddler抓包(HTTPS)(二)
    Android手机使用Fiddler抓包(HTTPS)(二)
    Fiddler使用详解(一)
    python2.x和python3.x中raw_input( )和input( )区别
  • 原文地址:https://www.cnblogs.com/glf2046/p/4885411.html
Copyright © 2011-2022 走看看