填充容器

发布时间:2017-1-17 8:48:20 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"填充容器",主要涉及到填充容器方面的内容,对于填充容器感兴趣的同学可以参考一下。

虽然容器帮你解决了打印的问题,填充容器的操作仍然同 java.util.Arrays 一样有缺陷。 与 Arrays 一样,Collections 也有一个实用的 static 方法集,其中包括有 fill()。此 fill() 方法也是用同一个对象的引用来填充容器的,并且只对 List 对象有用,而对 Set 或 Map 并不起作用。   //:c11:FillingLists.java // TheCollections.fill() method. import com.bruceeckel.simpletest.*; import java.util.*;   public   class FillingLists { private   static Test monitor = new Test(); public   static    void main(String[] args) {     List list = new ArrayList(); for(int i = 0; i < 10; i++)             list.add("");     Collections.fill(list,           "Hello");     System.out.println(list);     monitor.expect(new String[] { "[Hello,Hello, Hello, Hello, Hello, " + "Hello,Hello, Hello, Hello, Hello]"     });   } }   ///:~   此方法的作用有限,只能替换已经在 List 中存在的元素,并不能增加新元素。   为了编写更有趣的例子,我补充了带有 fill()方法的 Collections2 类(为便于使用,我将其 作为 com.bruceeckel.util的一部分),此方法是用一个生成器来添加元素,它使你可以 订制需要add()的元素个数。Collection 可以使用先前定义的 Generator 接口,但是 Map 需要它自己的生成器接口,因为对于 Map 每次调用 next()需要生成一对对象(一个“键” 与一个“值”)。下面是 Pair 类:   //:com:bruceeckel:util:Pair.java package com.bruceeckel.util;   public   class Pair { public Object key, value; public Pair(Object k, Object v) {     key = k;     value = v;   } }   ///:~   下面的生成器接口用来生成 Pair:   //:com:bruceeckel:util:MapGenerator.java package com.bruceeckel.util; public   interface MapGenerator { Pair next(); }                          ///:~   有了这些类,就可以开发一套与容器类一起使用的实用类了:   //:com:bruceeckel:util:Collections2.java // To fill anytype of container using a generator object. package com.bruceeckel.util; import java.util.*;   public   class Collections2 { // Fill anarray using a generator: public   static    void         fill(Collection c, Generator gen,          int count) { for(int i = 0; i < count; i++)       c.add(gen.next());   } public   static    void   fill(Map m, MapGenerator gen, int count) { for(int i = 0; i < count; i++) {       Pair p = gen.next();       m.put(p.key, p.value);     }   } public   static    class   RandStringPairGenerator implements MapGenerator { private Arrays2.RandStringGenerator gen; public RandStringPairGenerator(int len) {       gen = new Arrays2.RandStringGenerator(len);     } public Pair next() { return   new Pair(gen.next(), gen.next());     }   } // Defaultobject so you don't have to create your own: public   static RandStringPairGenerator rsp = new RandStringPairGenerator(10); public   static    class   StringPairGenerator     implements MapGenerator { private   int index = -1; private String[][] d; public StringPairGenerator(String[][] data){       d = data;     } public Pair next() { // Force theindex to wrap:       index = (index + 1) % d.length; return   new Pair(d[index][0], d[index][1]);     } public StringPairGenerator reset() {       index = -1; return   this;     }   } // Use apredefined dataset: public   static StringPairGenerator geography = newStringPairGenerator(CountryCapitals.pairs);       // Produce asequence from a 2D array: public   static    class StringGenerator      implements Generator{ private String[][] d; private   int position; private   int index = -1; public StringGenerator(String[][] data,           int pos) {       d = data;       position = pos;     } public Object next() { // Force theindex to wrap:       index = (index + 1) % d.length; return d[index][position];     } public StringGenerator reset() {       index = -1; return   this;     }   } // Use apredefined dataset: public   static StringGenerator countries = newStringGenerator(CountryCapitals.pairs, 0); public   static StringGenerator capitals = newStringGenerator(CountryCapitals.pairs, 1); }   ///:~   两个版本的fill()都需要一个参数,以确定向容器添加的元素个数。此外,对于 Map 有两种 生成器:RandStringPairGenerator,生成任意数量的成对的随机 String,其长度由构造 器的参数决定;StringPairGenerator,使用外面传入的二维 String 数组产生成对的 String。StringGenerator 也接受二维 String 数组为参数,但是生成一个单独的元素而不 是 Pair 对象。static rsp,geography, countries, capitals 等对象各自提供预建的生成 器,最后三者用到了所有的国家与首都。注意,如果你尝试创建很多的键值对,超过了以 上对象提供的可用数据,生成器会循环至数据集的起点,在将键值对存入 Map 时,重复的 内容会被忽略。   下面是预先定义的数据集,由国家的名字与首都组成:   //:com:bruceeckel:util:CountryCapitals.java package com.bruceeckel.util;   public   class CountryCapitals { public   static    final String[][] pairs = { // Africa     {"ALGERIA","Algiers"}, {"ANGOLA","Luanda"},     {"BENIN","Porto-Novo"}, {"BOTSWANA","Gaberone"},           {"BURKINA FASO","Ouagadougou"},     {"BURUNDI","Bujumbura"},     {"CAMEROON","Yaounde"}, {"CAPE VERDE","Praia"},     {"CENTRAL AFRICAN REPUBLIC","Bangui"},     {"CHAD","N'djamena"},  {"COMOROS","Moroni"},     {"CONGO","Brazzaville"}, {"DJIBOUTI","Dijibouti"},     {"EGYPT","Cairo"}, {"EQUATORIAL GUINEA","Malabo"},     {"ERITREA","Asmara"}, {"ETHIOPIA","Addis Ababa"},     {"GABON","Libreville"}, {"THE GAMBIA","Banjul"},     {"GHANA","Accra"}, {"GUINEA","Conakry"},     {"GUINEA","-"}, {"BISSAU","Bissau"},     {"COTE D'IVOIR (IVORY COAST)","Yamoussoukro"},     {"KENYA","Nairobi"}, {"LESOTHO","Maseru"},     {"LIBERIA","Monrovia"}, {"LIBYA","Tripoli"},     {"MADAGASCAR","Antananarivo"}, {"MALAWI","Lilongwe"},     {"MALI","Bamako"}, {"MAURITANIA","Nouakchott"},     {"MAURITIUS","Port Louis"}, {"MOROCCO","Rabat"},     {"MOZAMBIQUE","Maputo"}, {"NAMIBIA","Windhoek"},     {"NIGER","Niamey"}, {"NIGERIA","Abuja"},     {"RWANDA","Kigali"},     {"SAO TOME E PRINCIPE","Sao Tome"},     {"SENEGAL","Dakar"}, {"SEYCHELLES","Victoria"},     {"SIERRA LEONE","Freetown"}, {"SOMALIA","Mogadishu"},     {"SOUTH AFRICA","Pretoria/Cape Town"},     {"SUDAN","Khartoum"},     {"SWAZILAND","Mbabane"}, {"TANZANIA","Dodoma"},     {"TOGO","Lome"}, {"TUNISIA","Tunis"},     {"UGANDA","Kampala"},     {"DEMOCRATIC REPUBLIC OF THE CONGO (ZAIRE)", "Kinshasa"},     {"ZAMBIA","Lusaka"}, {"ZIMBABWE","Harare"}, // Asia     {"AFGHANISTAN","Kabul"}, {"BAHRAIN","Manama"},     {"BANGLADESH","Dhaka"}, {"BHUTAN","Thimphu"},     {"BRUNEI","Bandar Seri Begawan"},     {"CAMBODIA","Phnom Penh"},     {"CHINA","Beijing"}, {"CYPRUS","Nicosia"},     {"INDIA","New Delhi"}, {"INDONESIA","Jakarta"},     {"IRAN","Tehran"}, {"IRAQ","Baghdad"},     {"ISRAEL","Tel Aviv"}, {"JAPAN","Tokyo"},     {"JORDAN","Amman"}, {"KUWAIT","Kuwait City"},     {"LAOS","Vientiane"}, {"LEBANON","Beirut"},     {"MALAYSIA","Kuala Lumpur"}, {"THE MALDIVES","Male"},     {"MONGOLIA","Ulan Bator"},           {"MYANMAR (BURMA)","Rangoon"},     {"NEPAL","Katmandu"}, {"NORTH KOREA","P'yongyang"},     {"OMAN","Muscat"}, {"PAKISTAN","Islamabad"},     {"PHILIPPINES","Manila"}, {"QATAR","Doha"},     {"SAUDI ARABIA","Riyadh"}, {"SINGAPORE","Singapore"},     {"SOUTH KOREA","Seoul"}, {"SRI LANKA","Colombo"},     {"SYRIA","Damascus"},     {"TAIWAN (REPUBLIC OF CHINA)","Taipei"},     {"THAILAND","Bangkok"}, {"TURKEY","Ankara"},     {"UNITED ARAB EMIRATES","Abu Dhabi"},     {"VIETNAM","Hanoi"}, {"YEMEN","Sana'a"}, // Australiaand Oceania     {"AUSTRALIA","Canberra"}, {"FIJI","Suva"},     {"KIRIBATI","Bairiki"},     {"MARSHALL ISLANDS","Dalap-Uliga-Darrit"},     {"MICRONESIA","Palikir"}, {"NAURU","Yaren"},     {"NEW ZEALAND","Wellington"}, {"PALAU","Koror"},     {"PAPUA NEW GUINEA","Port Moresby"},     {"SOLOMON ISLANDS","Honaira"}, {"TONGA","Nuku'alofa"},     {"TUVALU","Fongafale"}, {"VANUATU","< Port-Vila"},     {"WESTERN SAMOA","Apia"}, // EasternEurope and former USSR     {"ARMENIA","Yerevan"}, {"AZERBAIJAN","Baku"},     {"BELARUS (BYELORUSSIA)","Minsk"},     {"GEORGIA","Tbilisi"},     {"KAZAKSTAN","Almaty"}, {"KYRGYZSTAN","Alma-Ata"},     {"MOLDOVA","Chisinau"}, {"RUSSIA","Moscow"},     {"TAJIKISTAN","Dushanbe"}, {"TURKMENISTAN","Ashkabad"},     {"UKRAINE","Kyiv"}, {"UZBEKISTAN","Tashkent"}, // Europe     {"ALBANIA","Tirana"}, {"ANDORRA","Andorra la Vella"},     {"AUSTRIA","Vienna"}, {"BELGIUM","Brussels"},     {"BOSNIA","-"}, {"HERZEGOVINA","Sarajevo"},     {"CROATIA","Zagreb"}, {"CZECH REPUBLIC","Prague"},     {"DENMARK","Copenhagen"}, {"ESTONIA","Tallinn"},     {"FINLAND","Helsinki"}, {"FRANCE","Paris"},     {"GERMANY","Berlin"}, {"GREECE","Athens"},     {"HUNGARY","Budapest"}, {"ICELAND","Reykjavik"},     {"IRELAND","Dublin"}, {"ITALY","Rome"},     {"LATVIA","Riga"}, {"LIECHTENSTEIN","Vaduz"},     {"LITHUANIA","Vilnius"}, {"LUXEMBOURG","Luxembourg"},     {"MACEDONIA","Skopje"}, {"MALTA","Valletta"},     {"MONACO","Monaco"}, {"MONTENEGRO","Podgorica"},     {"THE NETHERLANDS","Amsterdam"}, {"NORWAY","Oslo"},         {"POLAND","Warsaw"}, {"PORTUGAL","Lisbon"},     {"ROMANIA","Bucharest"}, {"SAN MARINO","San Marino"},     {"SERBIA","Belgrade"}, {"SLOVAKIA","Bratislava"},     {"SLOVENIA","Ljujiana"}, {"SPAIN","Madrid"},     {"SWEDEN","Stockholm"}, {"SWITZERLAND","Berne"},     {"UNITED KINGDOM","London"}, {"VATICAN CITY","---"}, // North andCentral America     {"ANTIGUA AND BARBUDA","Saint John's"},     {"BAHAMAS","Nassau"},     {"BARBADOS","Bridgetown"}, {"BELIZE","Belmopan"},     {"CANADA","Ottawa"}, {"COSTA RICA","San Jose"},     {"CUBA","Havana"}, {"DOMINICA","Roseau"},     {"DOMINICAN REPUBLIC","Santo Domingo"},     {"EL SALVADOR","San Salvador"},     {"GRENADA","Saint George's"},     {"GUATEMALA","Guatemala City"},     {"HAITI","Port-au-Prince"},     {"HONDURAS","Tegucigalpa"}, {"JAMAICA","Kingston"},     {"MEXICO","Mexico City"}, {"NICARAGUA","Managua"},     {"PANAMA","Panama City"}, {"ST. KITTS","-"},     {"NEVIS","Basseterre"}, {"ST. LUCIA","Castries"},     {"ST. VINCENT AND THE GRENADINES","Kingstown"},     {"UNITED STATES OF AMERICA","Washington, D.C."}, // SouthAmerica     {"ARGENTINA","Buenos Aires"},     {"BOLIVIA","Sucre (legal)/La Paz(administrative)"},     {"BRAZIL","Brasilia"}, {"CHILE","Santiago"},     {"COLOMBIA","Bogota"}, {"ECUADOR","Quito"},     {"GUYANA","Georgetown"}, {"PARAGUAY","Asuncion"},     {"PERU","Lima"}, {"SURINAME","Paramaribo"},     {"TRINIDAD AND TOBAGO","Port of Spain"},     {"URUGUAY","Montevideo"}, {"VENEZUELA","Caracas"},   }; }   ///:~   这是一个简单的String数组6。下面使用fill()与生成器做个简单的测试:   //:c11:FillTest.java import com.bruceeckel.util.*; import java.util.*;   public   class FillTest { private   static Generator sg =  new Arrays2.RandStringGenerator(7); public   static    void main(String[] args) {     List list = new ArrayList();     Collections2.fill(list, sg, 25);     System.out.println(list + "\n");     List list2 =      new ArrayList();     Collections2.fill(list2,Collections2.capitals, 25);     System.out.println(list2 +        "\n");     Set set = new HashSet();     Collections2.fill(set, sg, 25);     System.out.println(set +       "\n");     Map m = new HashMap();     Collections2.fill(m, Collections2.rsp, 25);     System.out.println(m +     "\n");     Map m2 =    new HashMap();     Collections2.fill(m2,Collections2.geography, 25);     System.out.println(m2);   } }   ///:~   有了这些工具就可以通过使用有趣的数据填充容器来测试各种容器了。

上一篇:飞鸽原创博客,真正的飞鸽官方博客
下一篇:mysql 命令及Sql 语句

相关文章

关键词: 填充容器

相关评论