关于JAVA TreeSet怎么删除中间元素的问题
答案:5 悬赏:70 手机版
解决时间 2021-02-01 10:15
- 提问者网友:骨子里的高雅
- 2021-01-31 23:50
关于JAVA TreeSet怎么删除中间元素的问题
最佳答案
- 五星知识达人网友:忘川信使
- 2021-02-01 00:14
快速失败说的是 创建迭代器后 使用非迭代器方法修改了集合 再使用原来的迭代器 就会抛出异常
一般没人这么写 都是创建迭代器后遍历 但是如果是多线程就可能在遍历的时候修改集合 所以说线程不安全
所以你用迭代器删除了以后跳出 再创建新迭代器遍历就行了
import java.util.Iterator;
import java.util.TreeSet;
public class TTTreeSeeeet
{
public static void main(String[] args)
{
TreeSetM=new TreeSet<>();
for(int i=0;i<10;M.add(i++));
Iteratorit=M.iterator();
while(it.hasNext())
{
Integer i=it.next();
if(i.equals(5))
{
M.remove(i);
break;
}
}
it=M.iterator();
while(it.hasNext())
System.out.print(it.next()+" ");
System.out.println();
}
}
一般没人这么写 都是创建迭代器后遍历 但是如果是多线程就可能在遍历的时候修改集合 所以说线程不安全
所以你用迭代器删除了以后跳出 再创建新迭代器遍历就行了
import java.util.Iterator;
import java.util.TreeSet;
public class TTTreeSeeeet
{
public static void main(String[] args)
{
TreeSet
for(int i=0;i<10;M.add(i++));
Iterator
while(it.hasNext())
{
Integer i=it.next();
if(i.equals(5))
{
M.remove(i);
break;
}
}
it=M.iterator();
while(it.hasNext())
System.out.print(it.next()+" ");
System.out.println();
}
}
全部回答
- 1楼网友:何以畏孤独
- 2021-02-01 05:00
一定要这样,就使用Iterator找到,然后使用remove删除了
- 2楼网友:忘川信使
- 2021-02-01 04:31
用 角标 是List接口 ,不是Set接口, 你的需求无法用jdk标准库满足, 建议你查看apache common-collections库, 那里扩展了很多,可能有你要的
- 3楼网友:行雁书
- 2021-02-01 03:03
请题主先列出有错误的代码。
- 4楼网友:轻雾山林
- 2021-02-01 01:41
TreeSet删除元素有三种方法:
ts.remove(object);//通过元素删除(如果遍历当前的TreeSet删除当前TreeSet中的元素会出现异常)
ts.retainAll(list);//保留传入集合内的元素
ts.removeAll(list);//删除集合内的元素
ts.remove(object);//通过元素删除(如果遍历当前的TreeSet删除当前TreeSet中的元素会出现异常)
ts.retainAll(list);//保留传入集合内的元素
ts.removeAll(list);//删除集合内的元素
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯