制作一种在arraylist中交换两个int位置的方法

时间:2013-10-15 12:04:10

标签: java arraylist

任何人都可以向我提供任何见解,为什么以下代码段会导致无法找到符号错误,  这个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;
}

5 个答案:

答案 0 :(得分:1)

错误原因:

swapArray.set(location1)

swapArray.get(location1)

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

可能的解决方案:

如果我没错,swapArray应为List类型。请检查并作为附注使用类似Eclipse的IDE,这可以节省大量时间。

可能会有用:

<强>更新

    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方法。

答案 1 :(得分:1)

假设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复制/粘贴代码,而不是在此处手动输入代码,因为您倾向于输入拼写错误和语法错误。

答案 2 :(得分:0)

这里有一个技巧可以使用

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

我更喜欢彼得的答案。但是如果你只是将你的字符串放在一个集合中,以便调用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);
相关问题