gpt4 book ai didi

java - java 中的 array_intersect

转载 作者:行者123 更新时间:2023-12-01 14:53:39 25 4
gpt4 key购买 nike

我在网上找到了这个片段,它使用整数在 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_yournamea_crushname 都是字符串数组。

最佳答案

代码:

    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 for every”或拿起一本 Java 书。

关于java - java 中的 array_intersect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14536245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com