📑
scrapbook
  • Introduction
  • 1. Concept
  • 1.1 EAI
  • 1.2 ESB
  • 1.3 EAI v.s. ESB
  • 1.4 SOA
  • 1.5 RESTful
  • 1.6 Microservices
  • 1.7 Microservice v.s. SOA
  • 1.8 Maintain HTTP State
  • 1.8.1 Cookie
  • 1.8.2 Session
  • 1.9 Put, Add, and Set
  • 1.10 Public Key & Private Key
  • 1.11 Message Digest & Hash Function
  • 1.12 Diffie - Hellman Key Exchange
  • 1.13 About IoC
  • 1.14 About AOP
  • 1.15 Spring - Pros and Cons
  • 1.16 Spring - Prototype in Singleton
  • 1.17 HTTP v.s. SPDY
  • 1.18 HTTP/2
  • 1.19 Securing REST Services
  • 1.20 Conway's Law
  • 1.21 大型網站架構演化發展歷程
  • 1.22 Java Generics
  • 1.23 MySQL HA經驗談
  • 2. Questions & Solutions
  • 2.1 海底撈幾根針
  • 2.2 塞不進去
  • 3. Relational Database
  • 3.1 SQL Join Type
  • 3.2 SQL Injection
  • 3.3 MySQL CHAR v.s. VARCHAR
  • 4. NoSQL
  • 4.1 CAP Theorem, ACID v.s. BASE
  • 4.2 Two-Phase-Commit
  • 4.3 RDB v.s. NoSQL
  • 4.4 Structured, Unstructured and Semi-structured Data
  • 4.5 Shard v.s. Replica
  • 4.6 ArrayList v.s. LinkedList
  • 4.7 HashSet v.s. TreeSet
  • 4.8 HashMap v.s. TreeMap
  • 4.9 ArrayList v.s. Vector
  • 4.10 HashMap v.s. HashTable
  • 4.11 Statement, PreparedStatement and CallableStatement
  • 4.12 Overflow of Digits
  • X. JVM
  • X.1 JVM System Threads
  • X.2 Garbage Collection
Powered by GitBook
On this page

Was this helpful?

2.2 塞不進去

Previous2.1 海底撈幾根針Next3. Relational Database

Last updated 5 years ago

Was this helpful?

先來講一下大概的情境:

我有一個List (此處稱listA), 是透過Arrays.asList構成的, 然後在某些場合下, 我會往這個listA裡面繼續塞值, 以利用來處理商業邏輯, 可是當條件判斷要往listA裡面塞值的時候, 就出現了以下這個exception:

java.lang.UnsupportedOperationException

查了一下, 才發現透過Arrays.asList建構出來的list, 是fixed-size list, 所以才會塞不進去...

這邊有也是踩到一樣的雷, 特此紀錄一下, 下面用一個簡單的方法以及單元測試說明一下可塞進去與不可塞進去的場合:

package idv.carl.scjp.collection.list;

import java.util.List;

/**
 * @author Carl Lu
 */
public class ListAddDemo {

    public static void addToList(String value, List<String> list) {
        list.add(value);
    }

}

原始碼

package idv.carl.scjp.collection.list;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 * @author Carl Lu
 */
public class ListAddDemoTest {

    @Test
    public void testAddToNonFixedSizeList() {
        List<String> nonFixedSizeList = new ArrayList<>();
        nonFixedSizeList.add("Que");
        ListAddDemo.addToList("Pa so!!!", nonFixedSizeList);
        assertEquals(2, nonFixedSizeList.size());
    }

    @Test(expected = UnsupportedOperationException.class)
    public void testAddToFixedSizeList() {
        List<String> fixedSizeList = Arrays.asList("Que", "pa");
        fixedSizeList.add("so");
    }

}

原始碼

一篇
點我
點我