【问题标题】:Making a method for swaping two int's position within an arraylist制作一种在arraylist中交换两个整数位置的方法
【发布时间】:2013-10-23 05:30:33
【问题描述】:

任何人都可以告诉我为什么下面的代码 sn-p 给出了找不到符号错误, 当给定数组列表名称时,应使用此 swap(),它将索引位置 1 的内容与位置 2 交换

干杯!

public static void swap(String swapArray, int location1, int location2) {
    int tempswap1 = swapArray.get(location1);
    int tempswap2 = swapArray.get(location2);
    swapArray.set(location1)=tempswap2;
    swapArray.set(location2)=tempswap1;
}

【问题讨论】:

  • swapArray 不是ArrayList,而是String。在 Java 中,Strings 是不可变的(无法修改)。

标签: java arraylist


【解决方案1】:

错误原因:

swapArray.set(location1)

swapArray.get(location1)

由于swapArrayString 类型,所以String 类中没有set 方法甚至get 方法。

可能的解决方案:

如果我没记错的话,swapArray 应该是 List 类型。请检查并作为旁注使用 IDE 像 Eclipse 这样可以节省您大量的时间。

可能会更有用:

更新:

    public static void swap(List swapArray, int location1, int location2) {
-------------------------------^
        int tempswap1 = swapArray.get(location1);
        int tempswap2 = swapArray.get(location2);
        swapArray.set(location1,tempswap2);
        swapArray.set(location2,tempswap1);
    }

假设您将一个列表传递给 swap 方法。

【讨论】:

  • swapArray 是用来输入我想交换的arraylist的名称,因为有多个,不使用字符串如何使用用户数据来实现这一点,谢谢!
  • @DavidMcDaid 您的方法签名错误,更新帖子。
【解决方案2】:

假设swapArray 是问题标题中提到的列表类型,您需要像这样交换值

swapArray.set(location1, tempswap2); // Set the location1 with value2
swapArray.set(location2, tempswap1); // Set the location2 with value1

错误是因为swapArray.set(location1)=tempswap2;。左侧是一个方法调用(set()),它返回一个值,而您试图将另一个值分配给一个值,这是非法的。您需要在赋值运算符的 LHS 上有一个变量。


另外,这应该是/已经是实际的方法签名

public static void swap(List<Integer> swapArray, int location1, int location2)
                        ^^^^^^^^^^^^^ - This is the type of the object you're passing. You needn't give the name of that object as such.      

旁注:始终记得从 IDE 复制/粘贴代码,而不是在此处手动输入,因为您往往会出现拼写错误和语法错误。

【讨论】:

    【解决方案3】:

    你可以在这里使用一个技巧

    public static <T> void swap(List<T> list, int pos1, int pos2) {
        list.set(pos1, list.set(pos2, list.get(pos1)));
    }
    

    【讨论】:

      【解决方案4】:

      字符串在 Java 中是不可变的。你不能改变它们。 您需要创建一个替换字符的新字符串。 检查这个线程: Replace a character at a specific index in a string?

      【讨论】:

        【解决方案5】:

        我更喜欢彼得的回答。但是,如果您只是将字符串放入集合中以调用 setter(无论如何都不存在),您可以使用本机代码完成所有操作。

        请记住,如果您正在执行大量字符串操作,则如果您需要线程安全,则应使用 StringBuffer;如果您的程序不是多线程的,则应使用 StringBuilder。因为如前所述,字符串实际上是不可变的——这意味着每次更改字符串时,实际上都是在销毁旧对象并创建新对象。

        如果起始点(例如 loc1)可以偏移 0,则此代码需要更智能一些,但原生字符串操作的总体思路是:

        String x = a.substring(loc1,loc1+1);
        String y = b.substring(loc2,loc2+1);
        a = a.substring(0, loc1) + y + a.substring(loc1);
        b = b.substring(0,loc2) + x + b.substring(loc2);
        

        【讨论】:

          猜你喜欢
          • 2017-10-22
          • 2011-10-19
          • 2018-11-06
          • 1970-01-01
          • 2015-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多