【问题标题】:ArrayList<class> collection.swap methodArrayList<class> collection.swap 方法
【发布时间】:2013-12-03 10:13:37
【问题描述】:

我搜索了很多网站,但唯一找到的是This link

我有一个 BSNode 类。我做了一个ArrayList&lt;BSNode&gt; data,现在我想交换两个变量,但我遇到了这个错误:

The type of the expression must be an array type but it resolved to ArrayList<BSNode>

有什么办法可以交换这两个吗?当我只想比较两个变量时,我只需在 BSNode 类中实现可比较并覆盖一个方法。但是我应该怎么做才能在数组列表中交换它们?

我有这个方法:

public static void permutation (ArrayList<BSNode> data, int k, int n) 

我想这样做:

 for (int i = k; i < n; i++) { 
     Collections.swap(data, data[k], data[i]); 
 } 

【问题讨论】:

  • 请分享您的代码。
  • 你能发布你的代码吗
  • @kocko 没有什么可分享的了:D 只有一个名为 BSNode 的类,它有一个构造函数和 getter 和 setter:private double prob;私有 int 密钥;私有 int 级别;私有 BSNode 父节点;私有 BSNode 离开;私有 BSNode 权利;和另一个算法类,我需要将 collection.swap 用于 ArrayList 数据。
  • 那你想换什么?从您的问题中不清楚...
  • 你为什么不用Collections.swap(data, k, i);

标签: java arraylist collections swap


【解决方案1】:

使用Collections.swap(data, k,i); 而不是Collections.swap(data, data[k], data[i]);

【讨论】:

    【解决方案2】:

    如 javadoc 中所见,Collections.swap 采用 List 参数和 2 个整数,表示您想要交换的元素。所以你正在寻找的解决方案是这样的

    Collections.swap(data, k,i);
    

    Collections.swap

    public static void swap(List<?> list, int i, int j)
    
        list - The list in which to swap elements.
        i - the index of one element to be swapped.
        j - the index of the other element to be swapped.
    

    【讨论】:

      【解决方案3】:

      你可以使用

      Collections.swap(List<?> list, int i, int j);
      

      【讨论】:

        猜你喜欢
        • 2013-11-14
        • 1970-01-01
        • 2016-07-21
        • 2015-11-14
        • 2016-08-27
        • 1970-01-01
        • 2021-11-04
        • 2014-10-23
        • 1970-01-01
        相关资源
        最近更新 更多