首页 > 解决方案 > Java中字符串数组的复制构造函数

问题描述

所以我目前正在开发一个为数组字符串列表和链接字符串列表重新创建方法的项目。ArrayStringList 和 LinkedStringList 都有一个 StringList 接口。我们不允许查看接口的源代码——只能查看 API 文档。对于每个类,我们必须为这两个类创建一个默认构造函数和复制构造函数。我已经运行了测试,默认构造函数都通过了,但是 ArrayStringList 复制构造函数不起作用,并且一直抛出“null”或“-1”的错误消息。我对继承和接口很陌生,我认为对象参数与​​字符串数组数据类型让我有点失望。

这是我到目前为止的代码,以及构造函数中使用的方法:

我的复制构造函数:

private String[] stringArray;
private int size;

public ArrayStringList(StringList sl) {
    size = sl.size();
    ArrayStringList asl = new ArrayStringList();
    for(int i = 0; i < size-1; i++) {
        if(sl.get(i) != null) {
            asl.set(i,sl.get(i).toString());
        } //if
    } // for
} // copy constructor

尺寸方法:

public int size() {
    return stringArray.length;
} // size

获取方法:

public String get(int index) {
    if(index < 0 || index >= size) {
        throw new IndexOutOfBoundsException("out of bounds");
} else {
        return stringArray[index];
    }
} //get

设置方法:

public String set(int index, String s) {
    String old = stringArray[index];
stringArray[index] = s;
    return old;
} // set

在项目中,拷贝构造函数的描述如下:

实现类必须显式定义一个复制构造函数。复制构造函数应该只采用接口类型 StringList 的一个参数。它应该使新构造的列表对象成为构造函数参数引用的列表的深层副本。因此,新列表对象的初始大小和字符串元素将与其他列表相同。需要明确的是,另一个列表可以是 StringList 接口的任何实现的对象。不应对对象的类型做出其他假设。

标签: javaarraysconstructorinterfacecopy-constructor

解决方案


public class ArrayStringList implements StringList {

  private static final int INITIAL_CAPACITY = 10;

  private String[] stringArray;
  private int size;

  public ArrayStringList(StringList sl) {
    stringArray = sl.toArray();
    size = stringArray.length;
  }


  public ArrayStringList() {
    stringArray = new String[INITIAL_CAPACITY];
    size = 0;
  }

  // TODO: Extract 'if-cascade' to an validate(..) method 
  @Override
  public String set(int index, String s) {
    if (index >= size) {
      throw new IndexOutOfBoundsException("")
    } else if (s == null) {
      throw new NullPointerException("the specified string is null");
    } else if (s.isEmpty()) {
      throw new IllegalArgumentException("specified string is empty");
    }
    String old = stringArray[index];
    stringArray[index] = s;
    return old;
  }

  // TODO: Check if posible to extend the stringArray
  @Override
  public boolean add(String s) {
    if (s == null) {
      throw new NullPointerException("the specified string is null");
    } else if (s.isEmpty()) {
      throw new IllegalArgumentException("specified string is empty");
    }

    if (size == stringArray.length) {
      int newListCapacity = stringArray.length * 2;
      stringArray = Arrays.copyOf(stringArray, newListCapacity);
    }
    stringArray[++size] = s;
    return true;
  }

  // TODO: implement other methods ...
}

请记住,此实现仍然存在错误,但您可以将其用作起点


推荐阅读