案例介绍:
开发一个容器用来存放键值对,键用来存放英文名字,值用来存放中文名字,对键值对使用内部类进行封装。
案例设计:
- 使用静态内部类封装键值对数据
- 容器默认容量大小为5,超过就扩容2倍
- 通过调用entryArray方法返回容器中的数据
Code Demo
import java.util.Arrays;
public class EntryDemo {
public static void main(String[] args) {
MyContainer container=new MyContainer();
container.put("Jack","杰克");
container.put("Jone","琼");
container.put("Jimmy","吉米");
//调用container的entryArrays方法,赋给直接通过外部类名调用静态内部类对象的数组
MyContainer.Entry[] entrys=container.entryArrays();
//输出键值对
for(int i=0;i<entrys.length;i++){
MyContainer.Entry entry=entrys[i];
System.out.println(entry.getKey()+"--"+entry.getValue());
}
}
}
class MyContainer{
//Entry对象的数组存放键值对,默认大小为5
public static Entry[] entrys=new Entry[5];
private int count=0;//下标
//对外提供一个接口向容器中存放封装好的数据(Entry对象)
public void put(String key,String value){
//创建独立的entry数组元素
Entry entry=new Entry();
//调用内部类中的set方法为键值对赋值
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);
}
//把键值对封装在内部类Entry中
public static class 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;
}
}
}