java內部類案例

biubiubiuo發表於2018-02-23

實現鍵值對的儲存輸出

import java.util.Arrays;

public class EntryDemoTest {
//實現鍵值對的儲存
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyContainer container = new MyContainer();
		container.put("a", "小明1");
		container.put("b", "小明2");
		container.put("c", "小明3");
		container.put("d", "小明4");
		
		MyContainer.Entry[] entrys = container.entryArray();
		for(int i = 0;i<entrys.length;i++) {
			MyContainer.Entry entry = entrys[i];
			System.out.println(entry.getKey()+"----"+entry.getValue());
		}
	}

}

class MyContainer{
	//定義,初識設定陣列容量
	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;
		if(count>entrys.length) {
			int newCapacity;
			newCapacity = entrys.length*2;
			entrys = Arrays.copyOf(entrys, newCapacity);
		}
	}
	
	//返回有資料的內容
	public Entry[] entryArray() {
		return Arrays.copyOfRange(entrys, 0 , count);
	}
	
	public static class Entry{//將鍵值對封裝在Entry裡,這是個靜態的!
		private String key;
		private String value;
		
		public void setKey(String key) {
			this.key = key;
		}
		public void setValue(String value) {
			this.value = value;
		}
		public String getKey() {
			return key;
		}
		public String getValue() {
			return value;
		}

	}
		
	
}

  

相關文章