无法在数组类型 char[] 上调用 add(char)


public static void Reverse(char[] val){
char[] ch = val;
for (int g = val.length - 1; g >= 0; g--) {
ch.add(val[g]);
}

我收到一条错误消息,说我无法将字符添加到字符列表中,但字符列表不是只包含字符吗?

//if you really want no side effects for the source array and no return:
public static void reverse(char[] value){
char[] ch = new char[value.length];
int i=value.length-1;
for(var c:value){
ch[i--]=c;
}
}
// if you want to do an in place reverse of the passed-in array:
public static void reverse2(char[] value){
int l=value.length-1;
for(int i=0; i<l/2; i++){
char c = value[i];
value[i]=value[l-i];
value[l-i]=c;
}
}

数组不是一个列表。char[]是数组。数组具有固定大小,因此您无法向其添加元素或从中删除元素。如果要使用列表,请修改代码:

public static void Reverse(List<Character> val){
List<Character> ch = val;
for (int g = val.size() - 1; g >= 0; g--) {
ch.add(val.get(g));
}

最新更新