stack中add()和push()的区别。

在stack中有自己添加元素的方法push();但是在操作过程中发现,add()同样可以添加元素至stack

那这两个方法有什么不同呢?

stack本身没有add()方法,但是继承的类vector有add方法同样vector的父类和实现接口List同样有add()方法。

1.返回值

push()方法返回值描述:

Returns:theitem argument

        而add()方法的返回值描述:

Returns:true (as specified byCollection.add),也就是会返回true 或者false。 2.插入目标位置 push()方法的插入位置:Pushes an item onto thetop of this stack. add方法插入位置:Appends the specified element to theend of this Vector. 可以很明显的看到在插入位置上,push方法插入stack的顶端,而add方法是插入在vector的底端, 这里有个逻辑反转的问题:因为vector和stack的实现方式同样是数组,所以在stack的add()类似与添加在数组的底端, stack的出入策略是后进先出,也就是vector的底也就是stack顶部。 贴出自己测试代码:

这里还有一个addElement()和add()方法的区别?

这两个方法最大的区别就是返回值不一样,在作用上基本没有区别。 add是实现List接口重写的方法,返回值为boolean。 addElement是Vector类中的特有方法,返回值是void。(粘贴自百度,认同)





你可能感兴趣的:(集合容器)