【问题标题】:Cannot invoke add(char) on the array type char[]无法在数组类型 char[] 上调用 add(char)
【发布时间】:2020-05-05 10:51:25
【问题描述】:
public static void Reverse(char[] val){
    char[] ch = val;
    for (int g = val.length - 1; g >= 0; g--) {
        ch.add(val[g]);
    }

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

【问题讨论】:

    标签: java list arraylist char character


    【解决方案1】:
    //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;
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      数组不是列表。 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));
          }
      

      【讨论】:

      • 我可以在数组中切换元素吗?
      • 嘿@javax,你可以使用List的add method进行切换。 List 类似于 Array 但主要用于自动扩展数组大小,所以如果你只是想交换元素,我建议你再问一个问题。
      猜你喜欢
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 2022-01-23
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多