class 的 toString 方法继承自 arrayList
toString methode for class inherrited from arrayList
我正在做一些自然语言处理,因此实现了一个句子 class 基本上是一个带有一些元信息的 ArrayList。我想覆盖它的 toString() 方法,它只是粘贴由空格分隔的字符串。我通过使用继承的 get 方法让它工作,但我想知道直接访问字段是否可能和更好(在效率和编码实践方面)。
这是我的class的简化版本:
public class Sentence extends ArrayList<String> {
int sentimentScore;
String Speaker;
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i =0; i < super.size(); i++){
sb.append(super.get(i));
sb.append(" ");
}
return sb.toString();
}
最好使用get()
方法。 Speed-wise,它不应该使您的代码变慢很多(如果您不这么认为,您应该在持有这种信念之前编写一个小程序来演示速度下降的影响)。更重要的是,ArrayList
没有暴露其内部字段,这是一个很好的设计。如果维护者决定更改 ArrayList
.
的内部实现,此设计会将任何未来 side-effect 屏蔽给其他人(扩展它的 sub-classes)
顺便说一句,您可能还想考虑另一种设计——而不是让 Sentence
扩展 ArrayList
,让 Sentence
包含 ArrayList
。这就是所谓的组合优于继承的原则。
来自维基百科:https://en.wikipedia.org/wiki/Composition_over_inheritance
Composition over inheritance (or composite reuse principle) in
object-oriented programming is the principle that classes should
achieve polymorphic behavior and code reuse by their composition (by
containing instances of other classes that implement the desired
functionality) rather than inheritance from a base or parent class.
This is an often-stated principle of OOP, such as in the influential
Design Patterns: "Favor 'object composition' over 'class
inheritance'."
我正在做一些自然语言处理,因此实现了一个句子 class 基本上是一个带有一些元信息的 ArrayList。我想覆盖它的 toString() 方法,它只是粘贴由空格分隔的字符串。我通过使用继承的 get 方法让它工作,但我想知道直接访问字段是否可能和更好(在效率和编码实践方面)。
这是我的class的简化版本:
public class Sentence extends ArrayList<String> {
int sentimentScore;
String Speaker;
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i =0; i < super.size(); i++){
sb.append(super.get(i));
sb.append(" ");
}
return sb.toString();
}
最好使用get()
方法。 Speed-wise,它不应该使您的代码变慢很多(如果您不这么认为,您应该在持有这种信念之前编写一个小程序来演示速度下降的影响)。更重要的是,ArrayList
没有暴露其内部字段,这是一个很好的设计。如果维护者决定更改 ArrayList
.
顺便说一句,您可能还想考虑另一种设计——而不是让 Sentence
扩展 ArrayList
,让 Sentence
包含 ArrayList
。这就是所谓的组合优于继承的原则。
来自维基百科:https://en.wikipedia.org/wiki/Composition_over_inheritance
Composition over inheritance (or composite reuse principle) in object-oriented programming is the principle that classes should achieve polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) rather than inheritance from a base or parent class. This is an often-stated principle of OOP, such as in the influential Design Patterns: "Favor 'object composition' over 'class inheritance'."