简体   繁体   English

如何编写通用方法来交换数组中项目的值?

[英]How do I write a generic method to swap values of items in an array?

I am trying to get this code to work.我试图让这段代码工作。 Most of the code was provided as a question but I just keep getting error after error that I simply to not understand.大多数代码都是作为问题提供的,但我只是不断地收到一个又一个错误,我根本不明白。

package generic.collections;
import java.util.ArrayList;

public static void <T> T swap(Collection<T>, T x, T y) {  
    T temp = a[x]; 
    a[x] = a[y]; 
    a[y] = temp;  
    } 
}

Your definition is off, first a void method can't return a T .您的定义已关闭,首先void方法不能返回T An array is not a Collection .数组不是Collection And x and y should be int (s).xy应该是int (s)。 Like,喜欢,

public static <T> void swap(T[] a, int x, int y) {
    T temp = a[x];
    a[x] = a[y];
    a[y] = temp;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM