gpt4 book ai didi

Java:继承、异常和 super 关键字

转载 作者:行者123 更新时间:2023-12-02 11:28:00 24 4
gpt4 key购买 nike

我有一个类X,它将ints保存在数组中:

public class X{
public int[] a;
public boolean[] allocated;

//constructor
public X(int len){
this.a = new a[len];
this.a = new allocated[len];
}


public void save(int tosave) throws ArrayStoreException{
int pos = 0;

for(int i=0; i<allocated.length; i++){
if(allocated[i] == true){
pos++;
}
}

if(pos == allocated.length){
throw new ArrayStoreExeption("no free space left");
}

a[pos] = tosave;
allocated[pos] = true;
}
}

还有我仍然需要实现的 Y 类和 save2...

public class Y extends X{

public void save2(int tosave){

// to be implemented
}

}

对于 save2 我希望它与 save 执行相同的操作,但异常(exception)的是,如果没有更多可用空间或发生 ArrayStoreException,那么我想要数组将大小加倍,然后将参数插入到数组中。

所以如果我这样做:

try{
super.save(tosave); // If no exception is thrown, does it save 'tosave'?

}catch(ArrayStoreExeption e){
System.out.println("noe free sapce left");
}

我的第一个问题是:如果try block 没有触发异常,catch block 之后的代码会执行吗?我不知道在哪里保存这段代码,如果没有剩余空间或抛出异常,该代码会使数组大小加倍。

有人可以帮忙吗?

编辑:我可以将代码放置在 catch block 内,使数组加倍吗?

最佳答案

  1. 您发布的代码存在许多语法错误。如果这个答案不能让您满意,我建议您修复这些问题并重新发布。

  2. 是的,您可以实现代码来扩展子类的 catch block 内的数组。它需要调用父类(super class)的 save 方法

  3. 您的子类可能应该重写 save 方法,而不是创建新的 save2 方法

  4. 使用 boolean 数组没有多大意义。鉴于您没有留下任何间隙,仅保留第一个未分配位置的单个索引不是更容易吗?

  5. 尽可能将您的成员变量保持私有(private)或 protected 。在这种情况下,如果子类要扩展数组,那么它可能需要受到保护。更好的办法是将其设为私有(private),并在父类(super class)中使用 protected 方法来扩展它。

  6. Arrays.copyOf 将为您进行扩展

所以把所有这些放在一起:

class Fixed {
private int size;
private int[] store;
private int index = 0;

public Fixed(int size) {
this.size = size;
store = new int[size];
}

public void save(int value) throws ArrayStoreException {
if (index == size)
throw new ArrayStoreException();
store[index++] = value;
}

protected void expand() {
size *= 2;
store = Arrays.copyOf(store, size);
}
}

class Expandable extends Fixed {
public void save(int value) {
try {
super.save(value);
} catch (ArrayStoreException x) {
expand();
save(value);
}
}
}

如果您希望避免递归,那么您可以使用:

public void save(int value) {
try {
super.save(value);
} catch (ArrayStoreException x) {
expand();
try {
super.save(value);
} catch (ArrayStoreException x) {
throw new IllegalStateException("Cannot save after expansion");
}
}
}

关于Java:继承、异常和 super 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com