有没有一种方法可以立即将一个对象存储到另一个类的列表中?

huangapple go评论75阅读模式
英文:

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 allMyShapes = new ArrayList();

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.

huangapple
  • 本文由 发表于 2020年9月18日 00:36:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63942518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定