我创建了一个通用的交换算法。为此,需要一个数组,并使用整数索引交换元素。
我为此创建了一个JUnit测试类,如果输出应该是错误,则无法确定使用什么而不是assertArrayEquals。
这是我的尝试:
@Test
public void testNull() {
GenericMethods gm = new GenericMethods();
String names[] = null;
Error err = null;
//String expectedOutput[] = { "Hugh", "Simon", "Ebrahim", "Diane", "Paula", "Andrew" };
assertArrayEquals(gm.swap(names, 1, 5), (err));
}
以下是使用的通用交换方法
package genericMethods;
import java.util.Arrays;
public class GenericMethods {
public static <T> T[] swap(T[] names, int index1, int index2) {
if(names == null){
return null; //This will return nothing if nothing has been selected
}
if ((index1 >= 0 && index1 < names.length) && (index2 >= 0 && index2 < names.length)) {
T string = names[index1];
names[index1] = names[index2];
names[index2] = string; //Will check if a valid name has been selected
}
return names;
}
public static void main(String[] args) {
String[] names = new String[] { "Hugh", "Andrew", "Ebrahim", "Diane", "Paula", "Simon" };
swap(names, 1, 5); //will swap Hugh with Simon
}
}