开发者

java - vector has always the same results

I read an .ini File and put every property into an temporary array which i put at the end into a vector - until here it works fine.

But if I want to access every array in that vector, I get ALWAYS the same results, which is impossible. I tried it with different ways, different loops and everything different, but always the same results, here is my actuall code:

    tmp2 = new String[2];
    for(Enumeration e=allPropertys.elements(); e.hasMoreElements();) {
        tmp2 = (String[])e.nextElement();
        for(int i = 0; i < tmp2.length; i++)
        {
            System.out.println(tmp2[i]);
        }
    }

And here is the code where I put everything into the vector:

    try {
        tmp = new String[2];

        prop = new Properties();
        prop.load(new FileReader("konfig.ini"));

        Enumeration e = prop.propertyNames();
        while (e.hasMoreElements()) {

            String key = (String)e.nextElement();
            String value = prop.getProperty( key );
            tmp[0] = key + " " + 开发者_JAVA技巧 value;
            tmp[1] = value;

            System.out.println("Property: " + tmp[0] + " und Value: " + tmp[1]);
            allPropertys.add(tmp);
        }
    }


My guess is that when you populate your vector, you reuse the same string array for every property. This makes you vector contain 10 times (10 being the number of entries) the same array:

String[] property = new String[2];
for (every line in the file) {
    property[0] = ...;
    property[1] = ...;
    vector.add(property);
}

This should be replaced by

for (every line in the file) {
    String[] property = new String[2];
    property[0] = ...;
    property[1] = ...;
    vector.add(property);
}

Also, note in your code snippet, you create a new String array to initialize your tmp2 variable, and then replace its value by the one in the vector. The initialization is unnecessary.


You are replacing the values inside the array and putting the very-same array into the collection once and again.

You must understand how objects and arrays work. You think that adding it to a collection copies it or something (that's why you initialize the array before the loop in the reading part, I think). It only adds the reference. You always work with references.

You must create a new array for each time you want to add it. Think of an array variable (or any object variable) as a reference to an object. As an arrow to the real thing. When you add it to the vector you are adding arrows to the same structure in memory (the same two buckets).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜