1

I need a to create collection constructor. This is a constructor copies all of its elements from my array into the new TimeArrayList.

My constructor looks like this so far

private E[] timeData;
private int capacity = 0;

public TimeArrayList(Collection<? extends E> c) {
    timeData = (E[]) new Object[capacity];
    for (int i = 0; i < timeData.length; i++) {
  //this is where  im having the problem
}
}

I do not know how to get the values from my array and create an Array List. I think I also have to put in an iterator somewhere also.

Rise LC
  • 37
  • 3
  • 6

3 Answers3

2

The simplest way to get an array of type First, you'll need to allocate space for the data:

timeData = new (E[]) new Object[c.size()];

After that you can add the contents of c, for example:

Edit: changed to use toArray as pointed out in comments.

c.toArray(timeData);

But really, the simplest is to take advantage of the standard library and forget manual use of arrays:

List<E> timeData;
...
// and in constructor:
timeData = new ArrayList<E>(c);
kiheru
  • 6,588
  • 25
  • 31
0

What I would do is check the number of elements in C, and also use an iterator to iterate over those elements and add them to your timeData array.

Also, as arynaq said, you can also use the toArray() method: see https://stackoverflow.com/a/3293970/1688441

public TimeArrayList(Collection<? extends E> c) {

        //Long way
        timeData = (E[]) new Object[c.size()];
        int element = 0;

        Iterator<? extends E> it = c.iterator();
        while(it.hasNext())timeData[element++] = it.next();

        //Short way
        timeData = c.toArray(timeData);     

    }
Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155
0

I would write it by this way without capacity:

 public class TimeArrayList<E> {

   private List<? super E>  timeData = null;

   public TimeArrayList(Collection<? extends E> src) {

     this.timeData = new ArrayList<E>(src.size());

     Iterator<? extends E> collectionIterator = src.iterator();

     for (int i = 0; collectionIterator.hasNext(); i++) {
         this.timeData.set(i, collectionIterator.next());
     }  
   }
}

The quizzical phrase ? super E means that the destination list may have elements of any type that is a supertype of E, just as the source list may have elements of any type that is a subtype of E.

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225