java解析java源码_JAVA语言-Java源码解析-Stack源码分析
一、簡介
stack類圖.png
棧是數據結構中一種很重要的數據結構類型,因為棧的后進先出功能是實際的開發中有很多的應用場景。Java API中提供了棧(Stacck)的實現。Stack類繼承了Vector類,而Vector類繼承了AbstractList抽象類,實現了List類,Cloneable接口,RandomAcces接口以及Serializable接口。
二、源碼閱讀
1.構造方法public?Stack()?{
}
創建一個空棧。
2.入棧pushpublic?E?push(E?item)?{
addElement(item);
return?item;
}
public?synchronized?void?addElement(E?obj)?{
modCount++;
ensureCapacityHelper(elementCount?+?1);
elementData[elementCount++]?=?obj;
}
入棧是一個同步的方法,調用Vector的addElement方法,也是一個同步方法,先將修改次數加一,之后調用ensureCapacityHelper確認數組有足夠的空間能夠容納新的元素。最后將元素新增到數組,即Vector的末尾。
3.出棧poppublic?synchronized?E?pop()?{
E???????obj;
int?????len?=?size();
obj?=?peek();
removeElementAt(len?-?1);
return?obj;
}
出棧同樣是一個同步方法,先定義一個泛型對象obj,獲取到數組長度len,然后調用peek()方法,獲取棧頂的元素賦值給obj,然后刪除棧頂元素。public?synchronized?E?peek()?{
int?????len?=?size();
if?(len?==?0)
throw?new?EmptyStackException();
return?elementAt(len?-?1);
}
很顯然,peek()方法直接調用了Vector的elementAt方法,該方法不刪除棧頂的元素。
4.判斷棧是否為空/**
*?通過數組長度判斷棧是否為空。
*
*?@return??true?if?and?only?if?this?stack?contains
*??????????no?items;?false?otherwise.
*/public?boolean?empty()?{
return?size()?==?0;
}
5.查詢元素到棧頂的距離/**
*?Returns?the?1-based?position?where?an?object?is?on?this?stack.
*?If?the?object?o?occurs?as?an?item?in?this?stack,?this
*?method?returns?the?distance?from?the?top?of?the?stack?of?the
*?occurrence?nearest?the?top?of?the?stack;?the?topmost?item?on?the
*?stack?is?considered?to?be?at?distance?1.?The?equals?*?method?is?used?to?compare?o?to?the
*?items?in?this?stack.
*
*?@param???o???the?desired?object.
*?@return??the?1-based?position?from?the?top?of?the?stack?where
*??????????the?object?is?located;?the?return?value?-1?*??????????indicates?that?the?object?is?not?on?the?stack.
*/public?synchronized?int?search(Object?o)?{
int?i?=?lastIndexOf(o);
if?(i?>=?0)?{
return?size()?-?i;
}
return?-1;
}
一個同步方法,找到指定元素o到棧頂的距離,可以看到用到了lastIndexOf方法,如果找不到元素,則返回-1。
三、總計
通過源碼我們可以看到Vector底層是一個數組,說明Stack的實現是通過數組來實現的,然后通過對數組的操作來模仿棧的各種功能。而且在源碼中Vector的很多方法都是synchronized 的,也就是說是線程安全,所以說在多線程中是可以安全使用的,不過這樣效率上肯定是會降低的。
本文由職坐標整理并發布,希望對同學們有所幫助。了解更多詳情請關注職坐標編程語言JAVA頻道
總結
以上是生活随笔為你收集整理的java解析java源码_JAVA语言-Java源码解析-Stack源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: java中菜单分几级_JavaWeb三级
 - 下一篇: map转字符串数组中 php_js将ma