星空网 > 软件开发 > Java

使用内部类开发一个存放数据的容器

案例介绍:开发一个容器用来存放键值对,键存放英文名字,值存放中文名字,对键值对使用内部类来进行封装;

案例设计:

①   使用静态内部类封装键值对数据;

②   容器默认大小为5,超过就扩容其2倍;

③   通过调用entryArrays方法返回容器中的数据;

 1 import java.util.Arrays; 2 public class EntryDemo{ 3   public static void main(String []args){ 4     MyContainer container=new MyContainer(); 5     container.put("jack","杰克"); 6     container.put("jay","周杰伦"); 7     container.put("john","约翰"); 8     container.put("rose","罗斯"); 9     container.put("jack","张三");10     11     MyContainer.Entry[] entrys=container.entryArrays();12     for(int i=0;i<entrys.length;i++){13       MyContainer.Entry entry=entrys[i];14       System.out.println(entry.getKey()+"--"+entry.getValue());15     }16   }17 }18 19 class MyContainer{20   //存放entry对象的数组,默认大小为521   private Entry[] entrys=new Entry[5];22   private int count=0;23   24   //对外提供一个接口向容器中存放封装好的数据25   public void put(String key,String value){26     Entry entry=new Entry();27     entry.setKey(key);28     entry.setValue(value);29     entrys[count++]=entry;//存放entry对象到数组中30     //数组的扩容31     if(count>=entrys.length){32       //扩容后的新数组大小33       int newCapacity=entrys.length*2;34       //把老数组中的数据复制到长度为newCapacity的新数组中35       entrys=Arrays.copyOf(entrys,newCapacity);36     }37   }38   39   //把容器中的有数据的内容返回40   public Entry[] entryArrays(){41     return Arrays.copyOfRange(entrys,0,count);42   }43   44   //把键值对封装在Entry对象中45   public static class Entry{46     private String key;47     private String value;48     public void setKey(String key){49       this.key=key;50     }51     public String getKey(){52       return key;53     }54     public void setValue(String value){55       this.value=value;56     }57     public String getValue(){58       return value;59     }60   }61 }

 




原标题:使用内部类开发一个存放数据的容器

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

跨境电商集货:https://www.goluckyvip.com/tag/35826.html
跨境电商技巧:https://www.goluckyvip.com/tag/35827.html
跨境电商技术培训:https://www.goluckyvip.com/tag/35828.html
跨境电商加班严重吗:https://www.goluckyvip.com/tag/35829.html
政策解读:https://www.goluckyvip.com/tag/3583.html
跨境电商加盟:https://www.goluckyvip.com/tag/35830.html
一夜之间大批卖家货物被偷,又迎大量Listing将被下架!跨境赚钱"好日子"到头了?:https://www.kjdsnews.com/a/1842260.html
一夜之间大批卖家货物被偷,又迎大量Listing将被下架!跨境赚钱"好日子"到头了?:https://www.goluckyvip.com/news/220219.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流