0

私は Java を初めて使用し、値の ArrayList を含む LinkedHashMap をロードしようとしています。API ベースのクエリ結果 (Salesforce) からクエリ結果の値を読み込もうとしています。

ここにエラーがあります:「別のメソッドで定義された内部クラス内の非最終変数ブレークダウンを参照できません」-ブレークダウン変数に赤で下線が引かれ、このメッセージが表示されます。以下の懸念のある行に注意してください。

コード

public LinkedHashMap<String, ArrayList<String>> sfFundIdsByContact;

    public ArrayList<String> getFundsIDsForContact(Contact aContact)
    {
        QueryResult queryResults = null;
        ArrayList<String> ids = new ArrayList<String>();
        int index = 0;
        Boolean done = false;
        String contactid = aContact.getId();
        String SCCPBId = null;

        if(sfFundIdsByContact == null || sfFundIdsByContact.size() <= 0){

       //Do the Salesforce API CALL and Return the results  
       ...          
       while (! done) 
       {        
        SObject[] records = queryResults.getRecords();

        for ( int i = 0; i < records.length; ++i ) 
            {
                    if(sfFundIdsByContact.containsKey(breakdown.getSalesConnect__Contact__c())){
                        sfFundIdsByContact.get(breakdown.getSalesConnect__Contact__c()).add(breakdown.getId());
                    } else {
//Line below in the add(breakdown.getId() - contains the error
                    sfFundIdsByContact.put(breakdown.getSalesConnect__Contact__c(), new ArrayList<String>() {{ add(breakdown.getId()); }});

        }

    }

すべての提案を歓迎します。

4

2 に答える 2

3

あなたのelseブロックでは、代わりに:

new ArrayList<String>() {{ add(**breakdown.getId()**); }}

あなたが使用することができます:

new ArrayList<String>(Arrays.asList(breakdown.getId())

または、単一の要素が必要なだけなので、一時的な varargs 配列の作成を回避するためにArrayList使用できます。Collections.singletonList

new ArrayList<String>(Collections.singletonList(breakdown.getId())

{ ... }後には、内部クラスのみであるnew ArrayList<>()の匿名サブクラスを作成します。ArrayList内部クラス内では、非finalローカル変数にアクセスできません。

于 2013-10-21T21:03:37.283 に答える
0

You can ease the code by always retrieving the List value in the for loop, then if it is null create a new one and add it to your Map, otherwise add the value to the list.

for (int i = 0; i < records.length; i++) {
    List<String> value = sfFundIdsByContact.get(breakdown.getSalesConnect__Contact__c());
    if (value == null) {
        value = new ArrayList<String>();
        sfFundIdsByContact.put(breakdown.getSalesConnect__Contact__c(), value);
    }
    value.add(breakdown.getId());
}

As a recommendation, change the definition of

LinkedHashMap<String, ArrayList<String>> sfFundIdsByContact

to

Map<String, List<String>> sfFundIdsByContact

Refer to What does it mean to "program to an interface"?

于 2013-10-21T21:17:52.797 に答える