zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java 容器的打印

JAVA容器 打印
2023-09-27 14:23:51 时间

Java容器类库中的两种主要类型,它们的区别在于容器中每个"槽"保存的元素个数

Clollection容器只能在保存一个元素,此类容器包括:

List,它以特定顺序保存一组元素

Set对于每个值都只保存一个对象,不能有重复元素

Queue 只允许在容器的一"端"插入对象,并从另一端移除对象(很像数据结构的队列)

Map在每个槽内保存了两个对象,即键和与之想关联的值

Map允许你将某些对象与其他一些对象关联起来的关联数组,

 

必须使用Arrays.toString()方法来产生数组的打印方式,但打印容器无需任何帮助

//: holding/PrintingContainers.java
// Containers print themselves automatically.
package object;
import java.util.*;
import static net.util.Print.*;

public class PrintingContainers {
  static Collection fill(Collection<String> collection) {
    collection.add("rat");
    collection.add("cat");
    collection.add("dog");
    collection.add("dog");
    return collection;
  }
  static Map fill(Map<String,String> map) {
    map.put("rat", "Fuzzy");
    map.put("cat", "Rags");
    map.put("dog", "Bosco");
    map.put("dog", "Spot");
    return map;
  }    
  public static void main(String[] args) {
    print(fill(new ArrayList<String>()));
    print(fill(new LinkedList<String>()));
    print(fill(new HashSet<String>()));
    print(fill(new TreeSet<String>()));
    print(fill(new LinkedHashSet<String>()));
    print(fill(new HashMap<String,String>()));//HashMap提供了最快的速度
    print(fill(new TreeMap<String,String>()));//TreeMap按比较的结果保存键
    print(fill(new LinkedHashMap<String,String>()));//LinkedhashMap按插入顺序保存键,并保留了HashMap的速度
  }
} /* Output:
[rat, cat, dog, dog]
[rat, cat, dog, dog]
[dog, cat, rat]
[cat, dog, rat]
[rat, cat, dog]
{dog=Spot, cat=Rags, rat=Fuzzy}
{cat=Rags, dog=Spot, rat=Fuzzy}
{rat=Fuzzy, cat=Rags, dog=Spot}
*///:~