gpt4 book ai didi

java - 关于在 Java 中使用 ArrayList 的问题?

转载 作者:行者123 更新时间:2023-12-01 19:22:38 25 4
gpt4 key购买 nike

真不知道这个标题合适不合适。

我有两个选择:选项 1:

Class A {
ArrayList<B> BList = new ArrayList<B>();

public B[] getBList() {
return (B[])BList.toArray();
}
}

Class Facade {
public B[] getAllB(){
A a = new A();
return a.getBList();
}
}

选项 2:

Class A {
ArrayList<B> BList = new ArrayList<B>();

public ArrayList getBList() {
return BList;
}
}

Class Facade {
public B[] getAllB(){
A a = new A();
ArrayList BList = a.getBList();
return (B[])BList.toArray();
}
}

我应该使用哪个选项?

最佳答案

使用集合类,除非您有特定原因使用数组。所以,我会选择选项 2。

还可以对您的代码提出许多其他评论。

首先,最好 program to an interface, not an implementation - 使成员变量BList上课A一个List<B>而不是ArrayList<B> 。另外,成员变量应该是 private (除非有充分的理由让它们不成为 private )。第三,尽可能使用泛型 - 为什么你的方法 getBList()返回原始 ArrayList ? Java 中变量的实际命名标准是 camel case ,以小写字母开头。所以不要调用成员变量BList ,但是bList (或其他更好的名称)。

class A {
private List<B> bList = new ArrayList<B>();

public List<B> getBList() {
return bList;
}
}

上课真的有必要吗Facade返回 B[]

要考虑的另一点是让你的类 A不可变,因为如果您从 A 获取列表,可能会发生意想不到的事情。对象,然后从列表中添加或删除元素(A 对象内的列表也将被更改,这可能会令人困惑)。您必须返回 getBList() 中列表的只读 View 。方法:

public List<B> getBList() {
return Collections.unmodifiableList(bList);
}

关于java - 关于在 Java 中使用 ArrayList 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3275498/

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