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())

或者,因为您只想要一个元素ArrayList,您可以使用Collections.singletonList它来避免创建临时可变参数数组:

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

The { ... } after the new ArrayList<>() creates an anonymous subclass of ArrayList, which is an inner class only. Inside an inner class you cannot access non-final local variables.

于 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 回答