# VBForums CodeBank > CodeBank - Java / J# >  Java - Collections/Arrays

## Dillinger4

The Collection interface provides a mechanism to turn a Collection into an Array using the methods <T> T[] toArray(T[] a) or Object[] toArray(). The first method will return a Array containing all the elements of the Collection with the array being that of the type provided in the method call. The second method just returns an array being of an  Object[] type. 

The Arrays class provides the opposite. A way to turn an array into a List using the List<T> asList(Array[] a) method. The List returned is of a fixed length with any attempts to add an element throwing an UnsupportedOperationException.


```
import java.util.*; 

public class G{
 public static void main(String[] args){
  List<String> sun = new ArrayList<String>(); 
  sun.add("Feel");
  sun.add("the");
  sun.add("power");
  sun.add("of");
  sun.add("the");
  sun.add("Sun");
  String[] s1 = sun.toArray(new String[0]); //Collection to array
  for(int i = 0; i < s1.length; ++i){
   String contents = s1[i]; 
   System.out.print(contents);
  }
  System.out.println();
  List<String> sun2 = Arrays.asList(s1); //Array back to Collection
  for(String s2: sun2){ 
    String s3 = s2; 
    System.out.print(s3); 
  }
 //sun2.add(new String("Hello")); // throws UnsupportedOperationException
 }
}
```

----------


## indianj

Hi Dillinger4,

your code looks great. i want payaround with java. i was wondering if i want to add strings into my StringArrySeq how would i do that? what do i do to print strings rather than double array? is it possible? let me know anything about it?

here is my code:
--------

/**
 * inderjit anjale
 */
//import java.math.*;
import java.text.DecimalFormat;

   // Invariant of the StringArraySeq class:
   //   1. The number of elements in the seqeunces is in the instance variable 
   //      manyItems.
   //   2. For an empty sequence (with no elements), we do not care what is 
   //      stored in any of data; for a non-empty sequence, the elements of the
   //      sequence are stored in data[0] through data[manyItems-1], and we
   //      don't care what's in the rest of data.
   //   3. If there is a current element, then it lies in data[currentIndex];
   //      if there is no current element, then currentIndex equals manyItems


public class StringArraySeq {
  private double[] data;
  private int manyItems;  // number of items in the sequence
  private int currentIndex;  // points to current item


/**
 * Initialize an empty sequence with an initial capacity of 10 doubles.
 */
  public StringArraySeq() {
    this(10);
  }

  public StringArraySeq( int capacity ) {
    if( capacity <= 0 )
        throw new IllegalArgumentException("..:: capacity must be > 0 ::..");
    data = new double[capacity];
    manyItems = 0;
    currentIndex = -1;
  }

  /**
   * Accessor method to determine the number of elements in this sequence
   * @return
   *  int: the number of elements in this sequence
   */
  public int getSize(){
    return manyItems;
  }


  /**
  * Accessor method to determine the current capacity of this sequence.
  *
  * @return
  *   int: the current capacity of this sequence
  */
  public int getCapacity(){
    return data.length;
  }

  public double getCurrent(){
      if( !isCurrent() )
     throw new IllegalArgumentException(".: No current index for empty bag :.");
      return data[currentIndex];
  }

     /**
      * Accessor method to determine whether this sequence has a specified
      * current element that can be retrieved with the <CODE>getCurrent()</CODE>
      * method.
      * @return
      *   boolean: true (there is a current element) or false (there is no
      *   current element at the moment).
      */
      public boolean isCurrent(){
        return (currentIndex >= 0 );
      }

      /**
       * Move forward, so that the current element is now the next element
       * in this sequence.
       *
       * @exception
       *  IllegalStateException:
       *    indicates that there is no current element, so advance may not
       *    be called.
       */
       public void advance(){
        if(!isCurrent())
          throw new IllegalStateException("There is not current element, so it can't advance");
	if( currentIndex < manyItems-1 )
	    //if( manyItems < currentIndex-1 )
	        ++currentIndex;
       }

       /**
        * Generate a copy of this sequence
        * @returns
        *   Object: a copy of this sequence as an Object.
        * @exception
        *   OutOfMemoryError:
        *     Indicates insufficient memory for creating the clone.
        */
        public Object clone(){
          StringArraySeq result;
          try
          {
            result = (StringArraySeq) super.clone();
          } catch(CloneNotSupportedException e)
          {
            throw new RuntimeException("This class does not implement Cloneable");
          }
          result.data = ( double[] ) data.clone();
          return result;
        }

        /**
         * Add a new element to this sequence before the current element. If
         * this new element would take this sequence beyond its current
         * capacity, then the capacity is increase before adding the new
         * element
         */
         public void addBefore( double element ){
          if( data1() )
              ensureCapacity();
          if( isEmpty() ) {
            currentIndex = 0;
            data[currentIndex] = element;
          }
          else {
            // shift items that are to the right of currentIndex
            // to the right by one.
            for( int i = manyItems; i > currentIndex; i--)
                 data[i] = data[i-1];
            data[currentIndex] = element;

            // currentIndex = 0;
            // ++manyItems = 0;
          }
          ++manyItems; // there's one more element
         }

         /**
          * Check and increase the capacity of the sequence, if necessary,
          * in order to add another element.
          */
          public void ensureCapacity(){
            if( data1() ){
              double[] array = new double[2 * manyItems + 1];
              System.arraycopy(data,0,array,0,manyItems);
              data = array;
            }
          }

          /**
           * Check if all the capacity has been consumed.
           * @return
           *  boolean:
           *  true (if no space left) or false (if space is available)
           */
           public boolean data1(){
            return (manyItems == getCapacity() );
           }

          /**
           * Check if the sequence is empty.
           * @return
           *  boolean:
           *  true (no items in sequence) or false (>= 1 item in sequence)
           */
           public boolean isEmpty(){
            return (manyItems == 0);
           }

           /**
            * Return a String displaying items in the sequence
            * @return
            *   String: shows the elements in sequence in set format.
            */
            public String toString(){
              DecimalFormat dataConfig = new DecimalFormat("##.###");
              String str = "";
              str += "{";
              for( int i = 0; i < manyItems; i++){
                   str += dataConfig.format(data[i]);
                   if( i != manyItems-1)
                       str += ", ";
                   if( (i+1)%10 == 0 )
                       str += "\n";
              }
              str += "}";
              return str;
            }

  /**
  * Print out a set representation of the sequence
  */
  public void print(){
    System.out.println(this);
   }

  public void addAfter(double element){
    if( isEmpty() ){
        data[0] = element;
        currentIndex = 0;
    }
    // make sure there's enough room
    else {
      if( data1() ) ensureCapacity();
      // increment currentIndex, and then put element
      // at currentIndex
      ++currentIndex;
      for( int i = manyItems; i > currentIndex; i-- ){
        data[i] = data[i-1];
      }
      data[currentIndex] = element;
    }
    ++manyItems;
    //--manyItems;
 }


  public boolean removeCurrent(){
    if( isEmpty())
        return false;
    else {
      if( manyItems == currentIndex + 1){
          --manyItems; // if pointing at last element in data.
          --currentIndex;
      }
      else {
        for( int i = currentIndex; i < manyItems; i++ )
             data[i] = data[i+1];
             --manyItems;
             //--currentIndex;
      }
    }
    return true;
  }



  public void start(){
    currentIndex = 0;
    currentIndex ++;
  }


public void trimToSize(){
  if( data.length > manyItems){
    double[] newDataArray = new double[manyItems];
    System.arraycopy(data,0,newDataArray,0,manyItems);
    data = newDataArray;
    //data1 = newarry
  }
}

 public String getString(String target){

 return true;	
 }


public static void main (String [ ] args) {
System.out.println("The data has entered this Double Array Sequence correctly.");
System.out.println();

  double [] d={12.4, 16.9,7.3,4.8};
  StringArraySeq das=new StringArraySeq();
  for (int j=0; j<d.length; j++)
  das.addAfter (d[j]);
  das.addBefore (11.5);
  das.print();
}

}

----------

