- import java.util.Arrays;
- public class EntryDemo{
- public static void main(String []args){
- MyContainer mc=new MyContainer();
- mc.put("1","a");
- mc.put("2","b");
- mc.put("3","c");
- mc.put("4","d");
- MyContainer.Entry [] entrys=mc.entryArrays();
- for (int i=0;i<entrys.length;i++){
- //取出数组
- MyContainer.Entry entry=entry[i];
- System.out.println(entry.getKey()+"-----"+entry.getValue());
- }
- }
- }
- class MyContainer{
- //存放entry对象的数组
- private Entry [] entrys=new Entry[5];
- private int count=0;
- //对外提供一接口向容器中存放封装好的数据
- public void put(String key,String value){
- Entry entry=new Entry();
- entry.setKey(key);
- entry.setValue(value);
- entrys[count++]=entry;//存放entry对象到数组
- if(count>entrys.length){
- //扩容后的容器大小
- int newcapacity=entrys.length*2;
- entrys=Arrays.copyOf(entrys,newcapacity);
- }
- }
- //把容器中的有数据的内容返回
- public Entry [] entryArrays(){
- return Arrays.copyOfRange(entrys,0,count);
- }
- //把键值对封装在Entry对象中
- public static class Entry{
- private String key;
- private String value;
- public void setKey(String key){
- this.key=key;
- }
- public String getKey(){
- return key;
- }
- public void setValue(String value){
- this.value=value;
- }
- public String getValue(){
- return value;
- }
- }
- }
复制代码
|
|