我发现这个在线代码段使用整数在java中创建了一个类似array_intersect的函数。
样品:
int[] intersect(int[] arr1, int[] arr2) {
int count = 0;
for(int a = 0; a < arr1.length; a++) {
for(int b = 0; b < arr2.length; b++) {
if(arr1[a] == arr2[b]) {
count++;
break;
}
}
}
int[] result = new int[count];
count = 0;
for(int a = 0; a < arr1.length; a++) {
for(int b = 0; b < arr2.length; b++) {
if(arr1[a] == arr2[b]) {
result[count++] = arr1[a];
break;
}
}
}
return result;
}
int[] arr1 = new int[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100,
95, 85, 75, 65, 55, 45, 35, 25, 15, 05,
10, 15, 20, 25, 30, 35, 40, 45, 50, 55};
int[] arr2 = new int[] {15, 25, 35, 45, 55,
12, 22, 32, 43, 52,
15, 25, 35, 45, 55};
int[] p1 = this.unique(arr1);
int[] p2 = this.unique(arr2);
int[] intersectResults = this.intersect(arr1, arr2);
for(int a = 0; a < intersectResults.length; a++) {
System.out.print(intersectResults[a] + " ");
}
但当我把它改为:
String[] intersect(String[] a_yourname, String[] a_crushname) {
int count = 0;
for(int a = 0; a < a_yourname.length; a++) {
for(int b = 0; b < a_crushname.length; b++) {
if(a_yourname[a] == a_crushname[b]) {
count++;
break;
}
}
}
String[] result = new String[count];
count = 0;
for(int a = 0; a < a_yourname.length; a++) {
for(int b = 0; b < a_crushname.length; b++) {
if(a_yourname[a] == a_crushname[b]) {
result[count++] = a_yourname[a];
break;
}
}
}
return result;
}
String[] flames = this.intersect(a_yourname, a_crushname);
//String[] p23 = this.unique(arr2);
System.out.println("heheh" +flames.length);
for(int a = 0; a < flames.length; a++) {
System.out.print(flames[a] + " ");
}
有人可以向我解释我在这里做错了什么吗?我真的不熟悉Java。
a_yourname
和a_crushname
都是字符串数组。
答案 0 :(得分:1)
代码:
String[] a = new String[] { "aa", "bb", "cc" };
String[] b = new String[] { "bb", "cc", "dd" };
Set<String> setA = new HashSet<String>(Arrays.asList(a));
List<String> listB = Arrays.asList(b);
setA.retainAll(listB);
System.out.println(setA);
您可以在此处查看结果: http://ideone.com/tKg5xa
如果你真的想把结果作为一个数组:
String[] out = setA.toArray(new String[setA.size()]);
如果您只想迭代结果,则无需使用数组。谷歌“每个人的Java”或拿起一本Java书。