java - 将 long[] 更改为 Set。错误消息 : The method addAll in the type Collections is not applicable for the arguments (Set<Long>, 长[])

标签 java arrays collections set hashset

在一项家庭作业中,我被要求在现有程序中创建一个名为 noDups() 的方法,该方法可以从先前排序的数组中删除重复项,而不会破坏顺序。该问题还指出它必须是一个具有 O(N) 的算法,并确保没有项目被移动超过一次,无论有多少重复项。

我最初尝试使用嵌套的 for 循环来循环并删除重复项,但发现这是 O(N^2)。我了解到你可以用 Set 来解决这个问题。我尝试编写方法来接收 long[] (程序使用的数组类型)数组并将其转换为集合,因为集合仅包含唯一值:

public long[] noDups(long[] target) { //Method for removing duplicates

        Set<Long> set = new HashSet<Long>();
        Collections.addAll(set, target);

        return target;
}

我不断收到标题中所述的错误:

"The method addAll(Collection, T...) in the type Collections is not applicable for the arguments (Set, long[])"

之前我的方法看起来像这样,但我有一个不同的错误:

public void noDups(long[] target){

    Set<long> set = new Hashset<long>(Arrays.asList(target));

我初始化集合错误吗?谁能告诉我如何消除错误或引导我朝正确的方向将 long[] 转换为 Set。谢谢!

最佳答案

如果您的数组已排序,则不需要嵌套的 for 循环。您应该能够遍历该数组一次,并且仅在与之前不同的情况下添加该项目。

List<Long> newList = new ArrayList<Long>();
for(Long l : target) {       
   if(newList.isEmpty() || !l.equals(newList.get(newList.size()-1))) {
      newList.add(l); 
   }
}

newList 应包含所有条目,没有任何重复项。

我没有方便的编译器来测试这个,但希望它有意义。

关于java - 将 long[] 更改为 Set。错误消息 : The method addAll in the type Collections is not applicable for the arguments (Set<Long>, 长[]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47083529/

相关文章:

javascript - 使用 JSON 数据填充 Javascript 数组

javascript - Node JS 在创建属性之前循环遍历数组

java - 与Java集合的交集

java - 配置 Apache Shiro 权限

java - JMS(或任何消息传递解决方案)是否适合追随者/追随者模型

arrays - 按螺旋顺序打印二维数组

scala - Scala 中的基本集合类型是什么?

java - 如何在java 1.8中从org.jboss.jca.adapters.jdbc.jdk8.WrappedConnectionJDK8转换为oracle.jdbc.OracleConnection

java - java RMI中远程对象的绑定(bind)代理

java - Collections.copy问题