public void setCapacity(long capacity) {
        if (capacity < MIN_HEADER_TABLE_SIZE || capacity > MAX_HEADER_TABLE_SIZE) {
            throw new IllegalArgumentException("capacity is invalid: " + capacity);
        }
        // initially capacity will be -1 so init won't return here
        if (this.capacity == capacity) {
            return;
        }
        this.capacity = capacity;

        if (capacity == 0) {
            clear();
        } else {
            // initially size will be 0 so remove won't be called
            while (size > capacity) {
                remove();
            }
        }

        int maxEntries = (int) (capacity / HpackHeaderField.HEADER_ENTRY_OVERHEAD);
        if (capacity % HpackHeaderField.HEADER_ENTRY_OVERHEAD != 0) {
            maxEntries++;
        }

        // check if capacity change requires us to reallocate the array
        if (hpackHeaderFields != null && hpackHeaderFields.length == maxEntries) {
            return;
        }

        HpackHeaderField[] tmp = new HpackHeaderField[maxEntries];

        // initially length will be 0 so there will be no copy
        int len = length();
        if (hpackHeaderFields != null) {
            int cursor = tail;
            for (int i = 0; i < len; i++) {
                HpackHeaderField entry = hpackHeaderFields[cursor++];
                tmp[i] = entry;
                if (cursor == hpackHeaderFields.length) {
                    cursor = 0;
                }
            }
        }

        tail = 0;
        head = tail + len;
        hpackHeaderFields = tmp;
    }
@Test
    public void testSetCapacity() {
        HpackHeaderField entry1 = new HpackHeaderField(FOO, BAR);
        HpackHeaderField entry2 = new HpackHeaderField(HELLO, WORLD);
        final int size1 = entry1.size();
        final int size2 = entry2.size();
        HpackDynamicTable table = new HpackDynamicTable(size1 + size2);
        table.add(entry1);
        table.add(entry2);
        assertEquals(2, table.length());
        assertEquals(size1 + size2, table.size());
        table.setCapacity(((long) size1 + size2) * 2); //larger capacity
        assertEquals(2, table.length());
        assertEquals(size1 + size2, table.size());
        table.setCapacity(size2); //smaller capacity
        //entry1 will be removed
        assertEquals(1, table.length());
        assertEquals(size2, table.size());
        assertEquals(entry2, table.getEntry(1));
        table.setCapacity(0); //clear all
        assertEquals(0, table.length());
        assertEquals(0, table.size());
    }