java list集合运算

 


list集合运算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
 
public class ListDemo {
 
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // TODO Auto-generated method stub
          List <String> listA = new ArrayList <String>();
          listA.add("aa");
          listA.add("bb");
          listA.add("cc");
           
          List <String> listB = new ArrayList <String>();
          listB.add("cc");
          listB.add("dd");
          listB.add("ff");
           
          List <String> listC = new ArrayList <String>();
                   
          listC = deepCopy(listA);
           
          //求并集
          listA.addAll(listB);
          System.out.println("--并集--" +listA);
          //--并集--[aa, bb, cc, cc, dd, ff]
     
          //交集
          listA = deepCopy(listC);
          listA.retainAll(listB);
          System.out.println("--交集--" +listA);
          //--交集--[cc]
          
           
          //差集
          listA = deepCopy(listC);
          listA.removeAll(listB);
          System.out.println("--差集--" +listA);
          //--差集--[aa, bb]
           
 
          //无重复并集
          listA = deepCopy(listC);
          listA.removeAll(listB);
          listA.addAll(listB);
          System.out.println("--无重复并集--" +listA);
          //--无重复并集--[aa, bb, cc, dd, ff]
 
           
    }
     
    public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException { 
        /**
         * 深拷贝
         */
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); 
        ObjectOutputStream out = new ObjectOutputStream(byteOut); 
        out.writeObject(src); 
 
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); 
        ObjectInputStream in = new ObjectInputStream(byteIn); 
        @SuppressWarnings("unchecked"
        List<T> dest = (List<T>) in.readObject(); 
        return dest; 
    }
}

  

posted @   一只小小的寄居蟹  阅读(3028)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示