英文:
Is there a way to store a object immediately to a another classes list?
问题
标题,我在考虑像这样的东西
Shapes s = new Shapes();
Circle c = new Circle("我们的", "参数");
Rectangle r = new Rectangle("我们的", "参数");
Shapes.addToList(c); // 我不想为每个创建的对象都这样做
Shapes.addToList(r);
因此,我想在初始化对象时将这些对象添加到“Shapes”列表中。
有什么想法吗?
英文:
Title, I am thinking something like this
Shapes s = new Shapes();
Circle c = new Circle("Our", "Parameters");
Rectangle r = new Rectangle("Our", "Parameters");
Shapes.addToList(c); // I don't want to do this for every object I create
Shapes.addToList(r);
So I want to add these object to the 'Shapes' list when I initialize a object.
Any ideas?
答案1
得分: 0
如果Circle和Square都继承自Shapes,那么在Shapes的构造函数中,您可以自动添加到列表中。在析构函数中,您希望将其移除。import java.util.*;
public class Shapes {
public static List
public Shapes() {
addToShapes(this);
}
static public void addToShapes(Shapes myShape) {
allMyShapes.add(myShape);
}
static public void dump() {
System.out.printf("存储的形状数量:%d\n", allMyShapes.size());
}
}
public class Foo {
public static void main(String[] args) {
Shapes myFirstShape = new Shapes();
Circle myCircle = new Circle();
Square mySquare = new Square();
Shapes.dump();
}
}
我没有实现析构函数。当然,这仅在您始终希望具有此行为时才起作用。
英文:
If Circle and Square both inherit from Shapes, then in Shapes constructor, you could automatically add to your list. In the destructor, you'd want to remove it.import java.util.*;
public class Shapes {
public static List<Shapes> allMyShapes = new ArrayList<Shapes>();
public Shapes() {
addToShapes(this);
}
static public void addToShapes(Shapes myShape) {
allMyShapes.add(myShape);
}
static public void dump() {
System.out.printf("Number of shapes stored: %d\n", allMyShapes.size());
}
}
public class Foo {
public static void main(String[] args) {
Shapes myFirstShape = new Shapes();
Circle myCircle = new Circle();
Square mySquare = new Square();
Shapes.dump();
}
}
I didn't implement the destructor. This only works, of course, if you always want this behavior.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论