Java使用内部类存放数据

import java.util.Arrays;


public class EntryDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
// 产生一个容器
MyContainer mycontainer = new MyContainer();
mycontainer.put("name1", "阿波罗");
mycontainer.put("name2", "缪斯");
mycontainer.put("name3", "宙斯");
MyContainer.Entry[] myentry = mycontainer.entryArrays();
for (int i = 0; i < myentry.length; i++) {
MyContainer.Entry entry = myentry[i];
System.out.println(entry.getKey() + "___" + entry.getValue());
}
}


}


class MyContainer {
/** 存放Entry对象的数组,默认大小为5 */
private Entry[] entrys = new Entry[5];
int count = 0; // 下标
// 对外提供一个接口向容器中存放封装好的数据,Entry对象


public void put(String key, String value) {
Entry entry = new Entry();
entry.setKey(key);
entry.setValue(value);
// 存放到entry对象数组
entrys[count++] = entry;
// 数组扩容
if (count >= entrys.length) {
// 扩容后新的数组的大小
int newCapacity = entrys.length * 2;
// 利用数组的拷贝的方法
entrys = Arrays.copyOf(entrys, newCapacity);
}
}


// 把容器中的数据返回
public Entry[] entryArrays() {
// 拷贝有效的数据返回
return Arrays.copyOfRange(entrys, 0, count);
}


public static class Entry {
/** 内部类把键值对封装在Entry对象中 */
private String key;
private String value;


public String getKey() {
return key;
}


public void setKey(String key) {
this.key = key;
}


public String getValue() {
return value;
}


public void setValue(String value) {
this.value = value;
}


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值