2016-03-07 175 views
1

我有一個方法來添加一個通用元素集合到我的數組,但不知道如何實現這一點。我象COLLECTION那樣代表了我一直遇到的代碼行。我不知道該寫些什麼來代替這個。我的陣列是一個圓環陣列。如何將一組元素添加到我的數組中?

import java.util.Collection; 
import java.util.Iterator; 

public class CircularArrayRing<E> implements Ring<E> { 

    public E[] elements; //array of E 

    private int capacity; 
    private int writePos = 0; 
    private int available = 0; 

    public CircularArrayRing(int size) { //circular array constructor 

     capacity = size; 

    } 


    public boolean add(E e) { 

     if(available < capacity){ 
      if(writePos >= capacity){ 
       writePos = 0; 
      } 
      elements[writePos] = e;  //add element e 
      writePos++; 
      available--; 
      return true; 
     } 

     return false; 

    } 

    public boolean addAll(Collection<? extends E> c) { 

     if(available < capacity){ 
      if(writePos >= capacity){ 
       writePos = 0; 
      } 
      elements[writePos] = COLLECTION; //how do add a collection of elements? 
      writePos++; 
      available++; 
      return true; 
     } 

     return false; 
    } 
} 
+1

迭代集合,增加每個元素的寫入位置並在該位置設置元素。它基本上與for(E e:c){add(e); }' - 我可能會這樣實現它。在執行循環之前,只要跟蹤返回值,如果你得到'false',或者更好地檢查'available> = c.size()', – Thomas

+1

注意:我猜'可用++;'不是你想要的'addAll()'。 – Thomas

+1

附加說明:'available 0'。 – Thomas

回答

3

怎麼樣迭代和觸發add()一個接一個呢?

public boolean addAll(Collection<? extends E> c){ 
    for(E e : c){ 
    add(e); 
    } 
} 
1

功能的方式。

c.forEach(this::add); 
0

下面是一些例子:

public void testCollectionAdd() { 
    if (!isAddSupported()) return; 

    Object[] elements = getFullElements(); 
    for (int i = 0; i < elements.length; i++) { 
     resetEmpty(); 
     boolean r = collection.add(elements[i]); 
     confirmed.add(elements[i]); 
     verify(); 
     assertTrue("Empty collection changed after add", r); 
     assertTrue("Collection size is 1 after first add", 
        collection.size() == 1); 
    } 

    resetEmpty(); 
    int size = 0; 
    for (int i = 0; i < elements.length; i++) { 
     boolean r = collection.add(elements[i]); 
     confirmed.add(elements[i]); 
     verify(); 
     if (r) size++; 
     assertEquals("Collection size should grow after add", 
        size, collection.size()); 
     assertTrue("Collection should contain added element", 
        collection.contains(elements[i])); 
    } 
} 

全部代碼在這裏:

http://code.openhub.net/file?fid=WKY7Buaz9RI_B0BqM_HKnkm6lqY&cid=9RkvURzZ1wM&s=How%20to%20Add%20a%20collection%20of%20elements%20to%20my%20array%3F&pp=0&fl=Java&ff=1&projSelected=false&filterChecked,=true&mp,=1&filterChecked=true&mp=1&ml=1&me=1&md=1#L79