问题描述:

There is the following data structure:

Vector<Cluster> clustersList;

During the iterative process I add new elements to clustersList.

Cluster c1 = getCluster();

clustersList.add(c1);

The problem is that at the last iteration the first element (((0)(2))) is substituted by the last one ((((0)(2))((1)(6)))), ie:

[((0)(2))]

[((0)(2)), ((1)(6))]

[((0)(2)), ((1)(6)), ((3)(7))]

[((0)(2)), ((1)(6)), ((3)(7)), ((5)(8))]

[(((0)(2))((1)(6))), ((1)(6)), ((3)(7)), ((5)(8)), (((0)(2))((1)(6)))]

The result must be:

[((0)(2))]

[((0)(2)), ((1)(6))]

[((0)(2)), ((1)(6)), ((3)(7))]

[((0)(2)), ((1)(6)), ((3)(7)), ((5)(8))]

[((0)(2)), ((1)(6)), ((3)(7)), ((5)(8)), (((0)(2))((1)(6)))]

How can I get such result?

P.S. I don't use any ID inside the class Cluster.

网友答案:

The first cluster is some object (from new Cluster()) whose content is overwritten by the value of the last element.

You would not have this conceptual problem, if the class were immutable like String. The solution (for now) would be to add at some place(s) a new Cluster().

P.S.

Use List<Cluster> clusterList = new ArrayList<>(); - the newer classes, a bit faster.

相关阅读:
Top