如何修复setProperty中的奇怪排序或者为Properties类添加

时间:2013-05-21 11:51:08

标签: java properties

我在setProperty的排序方面遇到了困境,或者为了属性类而陷入困境。

我的想法是我要保存已排序的属性文件。我已准备好排序类,但是当我执行 setProperty put 时,安排变得很奇怪。

Properties tmp = new Properties();
tmp.setProperty("A1","B");
tmp.setProperty("A2","B");
tmp.setProperty("A3","B");
tmp.setProperty("A4","B");
tmp.setProperty("A5","B");

执行 tmp.list(System.out)时的输出变为:

-- listing properties --
A4=B
A3=B
A2=B
A1=B
A5=B

使用 put 时也会采用相同的安排。

我不知道为什么..我只需要将已排序的属性保存在* .properties文件中。

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:4)

Properties类扩展Hashtable,因此未定义保证排序顺序。最好的方法是尝试TreeMap,因为它给出了键的自然排序顺序。但是,如果您想要saveload,则必须使用自己的逻辑,因为这些操作不会出现在TreeMap上。如果您想查看这些代码示例,请告诉我们。