Java 从字符串[]中删除重复项
我创建了一个webscraper来拉链接,我时不时地得到重复条目,我将它们存储在字符串[]的数组中,我抛出了几个循环来检查重复,但无法删除重复项Java 从字符串[]中删除重复项,java,arrays,string,Java,Arrays,String,我创建了一个webscraper来拉链接,我时不时地得到重复条目,我将它们存储在字符串[]的数组中,我抛出了几个循环来检查重复,但无法删除重复项 public static void checkForDupes(String[] links) { for (int i = 0; i<links.length; i++) { String check = links[i]; for (String link : links) {
public static void checkForDupes(String[] links) {
for (int i = 0; i<links.length; i++) {
String check = links[i];
for (String link : links) {
if (check.equals(link)) {
// remove link
}
}
}
}
publicstaticvoidcheckfordupes(字符串[]链接){
对于(int i=0;i),简单数组有固定数量的对固定位置的对象的引用。因此,不能删除对象,只能用其他方法替换它们或NULL,这会使整体处于数组的中间。这可能不是你想要的。
由于无法从数组中删除元素,因此需要将整个数组替换为只包含所需条目的新数组。但这会产生一个新问题:开始时,您必须指定目标数组的大小,但不知道最终需要的大小。因此,您需要增大数组的大小并存储真正的数组在另一个变量中使用长度使用LinkedList
,它在添加元素时支持可变大小和良好的性能
此外,这种嵌套循环在较大时往往会变得非常缓慢。当您有20个以上的条目时,在哈希集中收集值要比这种简单的for循环快得多,而且还消除了重复的副作用
一个非常类似的类是HashMap
,它不会消除重复项。你应该在谷歌上搜索解释哈希算法和哈希映射是如何工作的。这是一个非常有趣的话题
例如:
import java.util.Arrays;
import java.util.HashSet;
public class Main
{
public static void main(String[] args) throws Exception
{
String[] links = {"a","b","a","c","b","c","d","e","f"};
HashSet<String> set=new HashSet<>();
set.addAll(Arrays.asList(links));
System.out.println(set);
}
}
要从集合中读取单个元素,可以使用set.get(index)
以下示例显示了如何在没有HashSet的情况下实现相同的功能:
import java.util.Arrays;
import java.util.HashSet;
public class Main
{
public static void main(String[] args) throws Exception
{
String[] input = {"a", "b", "a", "c", "b", "c", "d", "e", "f"};
String[] output = new String[input.length];
int count = 0;
// Iterate over the input array
for (String in : input)
{
// Check if the string is already in the output array
boolean found=false;
for (String out : output)
{
if (in.equals(out))
{
found=true;
break; // break the inner for loop, no need to continue the search
}
}
if (!found)
{
output[count++]=in;
}
}
System.out.println(Arrays.toString(output));
}
}
产出:
[a, b, c, d, e, f]
[a, b, c, d, e, f, null, null, null]
请注意我是如何简化for循环的。还请注意,输出数组包含一些未使用的空格。计数器变量包含数组的实际使用大小。为什么不使用Set
数据结构?您可以尝试这样的方法将字符串数组转换为Set。Set Set Set=new HashSet(Arrays.asList(array));我会试试这个,谢谢bothi会看看这个谢谢,我们在大学还没有看过HashMaps,如果你必须用传统数组来解决这个问题,然后在循环之前创建一个新的空数组,然后将所有想要的条目复制到目标数组中,那么这些看起来会更有用。去掉重复项。