栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Java复制堆栈?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Java复制堆栈?

只需使用Stack类的clone()方法(它实现Cloneable)。

这是一个使用JUnit的简单测试用例:

@Test   public void test(){    Stack<Integer> intStack = new Stack<Integer>();    for(int i = 0; i < 100; i++) {        intStack.push(i);    }    Stack<Integer> copiedStack = (Stack<Integer>)intStack.clone();    for(int i = 0; i < 100; i++)     {        Assert.assertEquals(intStack.pop(), copiedStack.pop());    }}

编辑:

tmsimont:这会为我创建“未经检查或不安全的操作”警告。有什么办法做到这一点而不会产生此问题?

我最初回答说警告是不可避免的,但实际上使用

<?>
(通配符)-typing 是可以避免的:

@Testpublic void test(){    Stack<Integer> intStack = new Stack<Integer>();    for(int i = 0; i < 100; i++)    {        intStack.push(i);    }    //No warning    Stack<?> copiedStack = (Stack<?>)intStack.clone();    for(int i = 0; i < 100; i++)    {        Integer value = (Integer)copiedStack.pop(); //Won't cause a warning, no matter to which type you cast (String, Float...), but will throw ClassCastException at runtime if the type is wrong        Assert.assertEquals(intStack.pop(), value);    }}

基本上,我想说的是您仍在从

?
(未知类型)到进行未经检查的强制转换
Integer
,但是没有警告。就个人而言,我还是更喜欢直接投射
Stack<Integer>
并使用禁止显示警告
@SuppressWarnings("unchecked")



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410298.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号