# 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 set = new HashSet();
        set.add(s[0]);
        for(int i = 1;i < n;i++){
            Set 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 set = new HashSet();
        set.add(s[0]);
        for(int i = 1;i < n;i++){
            List 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());

    }
}