In the process of the interview, forget the list can also do orthogonal set operation, this is also a common data problem ah, this is also a common data structure problem---collection, the process of interview has not thought of this data structure
An operation in Java that has integrated and intersected the API.
Code: (from http://pengyan5945.iteye.com/blog/1311597)
Intersection API: Use Retainall to
The API of the RemoveAll: first and then AddAll
Importjava.util.ArrayList;ImportJava.util.HashSet;Importjava.util.List;ImportJava.util.Set; Public classListtest { Public Static voidMain (string[] args) {testintersection (); TestUnion (); Testintersectionset (); } Private Static voidtestintersection () {List<String> List1 =NewArraylist<string>(); List<String> List2 =NewArraylist<string>(); List1.add ("ABC"); List2.add ("abc")); List1.add ("123"); List2.add ("123"); List1.add ("ABC"); List2.add ("XYZ"); List1.removeall (LIST2); List1.addall (LIST2); System.out.println ("The number of elements in the set is:" +list1.size ()); } Private Static voidTestintersectionset () {List<String> List1 =NewArraylist<string>(); List<String> List2 =NewArraylist<string>(); List1.add ("ABC"); List2.add ("abc")); List1.add ("123"); List2.add ("123"); List1.add ("ABC"); List2.add ("XYZ"); Set<String> set =NewHashset<string>(); Addlist2set (set, List1); Addlist2set (set, List2); System.out.println ("The number of elements in the set is:" +set.size ()); } Private Static voidtestunion () {List<String> List1 =NewArraylist<string>(); List<String> List2 =NewArraylist<string>(); List1.add ("ABC"); List2.add ("abc")); List1.add ("123"); List2.add ("123"); List1.add ("ABC"); List2.add ("XYZ"); List1.retainall (LIST2); System.out.println ("The number of intersection elements is:" +list1.size ()); } Private Static voidAddlist2set (set<string> set,list<string>list) { for(String str:list) {set.add (str); } }}View Code
Java and intersection operations