2012-03-04 3 views
4

Javaの:新しいプロパティ(...)と、新たな性質の違い()のputAll(...)

final Properties properties = new Properties(System.getProperties()); 

final Properties properties = new Properties(); 
    properties.putAll(System.getProperties()); 

の違いは何私はこれを見てきましたfix commit in JBoss ASとして変更します。

+0

「固定」コードのスニペットはどれですか? – home

+0

第2のもの。リンクを追加しました。 –

答えて

6

は違いを示す例です:最初のケースで

import java.util.*; 

public class Test { 
    public static void main(String[] args) { 
     Properties defaults = new Properties(); 
     defaults.setProperty("x", "x-default"); 

     Properties withDefaults = new Properties(defaults); 
     withDefaults.setProperty("x", "x-new"); 
     withDefaults.remove("x"); 
     // Prints x-default 
     System.out.println(withDefaults.getProperty("x")); 

     Properties withCopy = new Properties(); 
     withCopy.putAll(defaults); 
     withCopy.setProperty("x", "x-new"); 
     withCopy.remove("x"); 
     // Prints null 
     System.out.println(withCopy.getProperty("x")); 
    } 
} 

を、私たちは「X」プロパティの新しいデフォルト以外の値を追加し、それを削除しています。私たちが "x"を求めるとき、実装はそれが存在しないことを発見し、代わりにデフォルトを調べます。

2番目のケースでは、がデフォルトのであることを知らずに、デフォルト値をプロパティにコピーしています。これらはプロパティの値です。次に、「x」の値を置き換えて、それを削除します。 "x"を求めるとき、実装はそれが存在しないことに気付くでしょうが、それを調べるデフォルトがないので、戻り値はnullです。

2

最初のプロパティは、デフォルトとして設定されています。 2番目の変数はデフォルト以外の値として設定されます。ここで

+0

2番目はお勧めしません。ドキュメントから: "プロパティはHashtableから継承されるので、putオブジェクトとputAllメソッドはPropertiesオブジェクトに適用できます。キーや値が文字列でないエントリを呼び出し側が挿入できるので、その使用は強く推奨されません。 – ebaxt

関連する問題