Search code examples
javaexceptioncollectionsmapsunsupportedoperation

UnsupportedOperationException when inserting array into Map


I am getting an UnsupportedOperationException when inserting array into Map. The inputs to the map are correct. Is there any proper way I can get insert properly and return the data?

    public static Map<String, ProductClassPeriodData[]> getPeriodsByAgreement(String[] productClassIds,String agreementId) 
    {
        Map data = Collections.EMPTY_MAP;
        for (int i = 0; i < productClassIds.length; i++)
        {
            ProductClassPeriodData[] periodData = getInstance().getProductClassPeriodsByAgreement(productClassIds[i], agreementId);
            data.put(String.valueOf(i), periodData);
        }
        return data;
    }

Solution

  • Collections.EMPTY_MAP is immutable, there for this operation is not supported.

    /**
     * The empty map (immutable).  This map is serializable.
     *
     * @see #emptyMap()
     * @since 1.3
     */
    @SuppressWarnings("rawtypes")
    public static final Map EMPTY_MAP = new EmptyMap<>();
    

    Instead use

    Map<String, ProductClassPeriodData[]> data = new HashMap<>();