本文介绍了为什么Java Enumeration不按顺序返回属性列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个可以更改语言的简单程序,我会在字符串数组中转换myBundle.properties文件中的属性列表。

I'm creating a simple program with the possibility to change the language and I would convert the list of properties in the file myBundle.properties in a String array.

这是文件myBundle.properties:

This is the file myBundle.properties:

 #default
 test1=Hello1
 test2=Hello2
 test3=Hello3
 test4=Hello4
 test5=Hello5
 test6=Hello6

这是Java代码:

import java.util.*;

class BundleTest {

    BundleTest() {
        String[] s = returnStringArray(Locale.ENGLISH);
        for(int i=0; i<s.length; i++) {
            System.out.println(s[i]);
        }
    }

    private String[] returnStringArray(Locale language) {
        try {
            ResourceBundle labels = ResourceBundle.getBundle("myBundle", language);
            Enumeration<String> keys = labels.getKeys();
            Vector v = new Vector();
            String key = null;
            while (keys.hasMoreElements()) {
                v.add(keys.nextElement());
            }
            String[] s = new String[v.size()];
            for(int i=0; i<s.length; i++) {
                s[i] = (String)v.elementAt(i);
            }
            return s;
        } catch (MissingResourceException mre) {
            System.out.println("Risorse della lingua non trovate!");
            return null;
        }
    }

    public static void main(String[] args) {
        new BundleTest();
    }
}

但令人惊讶的是,当我执行程序时,它返回我按照随意的顺序把弦。为什么Enumeration有这种奇怪的行为?

But, surprisingly, when I execute the program it returns me the strings in a casual order. Why have Enumeration this strange behavior?

bash-4.1$ java BundleTest
test1
test6
test4
test5
test2
test3


推荐答案

我不知道ResourceBundle类的确切细节,但是在查看代码示例时,似乎它具有键/值对。

I do not know the exact details of the ResourceBundle class, but when looking at your code example, it seems that it has key/value pairs.

这表明它将其内容存储在中。 (同样,因为我不知道ResounrceBundle,这是预感)
HashMap键(和值)是无序的,因为它们的存储方式使得可以很容易地找到给定键的值。

This suggests that it stores its content in an HashMap. (Again, as I do not know ResounrceBundle, this is a hunch)HashMap keys (and values) are unordered as they are stored on such a way that the value can be easily found for a given key.

这篇关于为什么Java Enumeration不按顺序返回属性列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 19:57