# Set异常ConcurrentModificationException
ConcurrentModificationException异常:
当方法检测到对象的并发修改,但不允许这种修改时,抛出此异常。
import java.util.*; public class Main{ public static void main(String str[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int s[] = new int[n]; for(int i = 0;i < s.length;i++){ s[i] = sc.nextInt(); } Arrays.sort(s); Set<Integer> set = new HashSet<Integer>(); set.add(s[0]); for(int i = 1;i < n;i++){ Set<Integer> tmp = set; for(int t : tmp){ //迭代时tmp和set其实是同一个,并发导致错误。 set.add(s[i]+t); if(s[i] - t < 0){ set.add(t - s[i]); }else if(s[i] - t > 0){ set.add(s[i] - t); } } } System.out.println(set.size()); } }
import java.util.*; public class Main{ public static void main(String str[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int s[] = new int[n]; for(int i = 0;i < s.length;i++){ s[i] = sc.nextInt(); } Arrays.sort(s); Set<Integer> set = new HashSet<Integer>(); set.add(s[0]); for(int i = 1;i < n;i++){ List<Integer> tmp = new ArrayList<>(); //创一个新的表存储数据。 for(int t: set){ tmp.add(t); } for(int t : tmp){ set.add(s[i]+t); if(s[i] - t < 0){ set.add(t - s[i]); }else if(s[i] - t > 0){ set.add(s[i] - t); } } } System.out.println(set.size()); } }
本文作者:Canyooo
本文链接:https://www.cnblogs.com/canyooo/p/15826422.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步