Collection.toArray

Why does the Collection<E> interface have a method
Object[] toArray()instead of
E[] toArray()?
I bet there is a reason, but it is not obvious to me what the reason might be ...

If you tried to compile that class, I believe that the second, third, and sixth lines will emit compiler errors.
I don't believe that it is legal to declare an array of E's.It compiles. Look at Collection.toArray(T[]) for another example, or section 7.3 in the generics tutorial.
I guess the problem with the method in question, if defined as E[] toArray(), is that it should return an array of the collection's element type in order to be correct (do what it says it does). So:
List<Something> list = new ArrayList<Something>();
list.toArray();  // <--- would return a Something[]But, if you replace Something with a parameterized type, you can't have an array of it. So you can have a List<Filter<String>>, but what does its toArray() method return? It could return an array of the raw type (Filter) of E but how do you declare that?
CollImpl ducks around this somewhat, because you can't create one with E as a parameterized type in the first place, due to the constructor. But the contracts java.util.Collection specifies should be able to be upheld by all implementations.
That's the issue as I see it anyway, but maybe there's more to it.
Mark

Similar Messages

  • Collection.toArray() weird ?

    How come java throws exception with this ?
    Vector v = new Vector();
    v.add(new Float(1.0));
    v.add(new Float(1.0));
    Float[] f = (Float []) v.toArray() ;
    why can't I cast Object[] returned by toArray() method of collection. How is this method different for toArray(Object [])? How to work with toArray() according to my program ?

    Hi there
    This is because v.toArray() - returns an Object[] containing references to two Float objects (which does not suddenly classify as an array of type Float - right ?)
    Here one solution to your problem:
            Vector v = new Vector();
            v.add(new Float(1.0));
            v.add(new Float(1.0));
            //Float[] f = (Float []) v.toArray() ;
            int elements = v.size();
            Float[] f = new Float[elements];
            for (int i = 0; i < elements; i++) {
                f[i] = (Float)v.elementAt(i);
            }Kind regs,
    Hjembaek

  • Collection toArray method problem

    everything ok
    assets = new Asset[alAsset.size()];
    alAsset.toArray(assets);
    null pointer exception
    assets = new Asset[alAsset.size()];
    assets = (Asset[])alAsset.toArray();
    why?
    Do any one explain this?

                Vector v = new Vector();
                String str1 = "abc";
                String str2 = "123";
                v.add(str1);
                v.add(str2);
                String strs[] = new String[v.size()];
                v.toArray(strs);                //It work
    //            strs = (String[])v.toArray(); //It doesn't work
                for(int i=0;i<strs.length;i++)
                    System.out.println((String)strs);
    Class case exception,sorry for the latest mistaken make you inconvenient

  • How to use results of ejbfind methods when it is a collection ?

    How to use ejbFind methods result , when it is a collection ?
    Hi thank you for reading my post.
    EJB find methods return a collection , i want to know how i can use that collection ?
    should i use Collection.toArray() and then use that array by casting it?
    what is DTOs and ho i can use them in this case?
    How i can use the returned collection is a swing application as it is a colection of ejbs ?
    Should i Cast it back to ejb class which it comes from or some other way ?
    for example converting it to an array of DTO (in session bean) and return it to swing application ?
    or there are some other ways ?
    Thank you

    Hi
    pleas , some one answer
    Collection collection = <home-interface>.<finderMethod>;
    Iterator iter = collection.iterator();
    while (iter.hasNext()) {
    <remote-interface> entityEJB = (<remote-interface>) iter.next();
    } what if i do the above job in session bean and convert the result to a DTO and pass the dto back ?
    thank you

  • SET into string array using toArray()

    I have a object java.util.Set collection and I want to convert all the elements
    into a string array but i don't know why it is not working in my JSP page...
    as i am trying to use toArray() method
    i have tried this          
    String[]  arr = collection.toArray();this
    String[]  arr = (String []) collection.toArray();could you please tell me the right way to aplly it...
    thanks in advance....:)

    I am using session listener which map sessions and it stores sessionid which i hope is a string
    when i directly print this set object it shows
    [ED0EF456BD1EE956A069340633C8DB87,UT0EF456BD1EE956A069340633C8DB34,RD0EF456BD1EE956A069340633C8DB98]
    Message was edited by:
    hunterzz

  • How do I convert an arrayList to an array []

    I want to create a generic method that I can pass a Collection ( An ArrayList if I have to be specific ) and also tell this method the underlying Object type the Collection contains and have it call the Collections.toArray method and create an array [] of the type I specify.
    Part of the problem is how do I have the method resolve the return type at run time and how do I use the Class variable to tell it the type of objects the Collection holds.
    Fo instance I load an ArrayList with 3 MyClass objects.
    I want to pass this to the method and have it return me an array of Type MyClass containing 3 items.
    I don't want to have to be tied to a method with the signature
    public MyClass [] convert( ArrayList myList  ){ ... }Thanks ...

    Since it is an "old system" I doubt that is feasible. Also I believe that this was intentionally left out of the API because specifying the array type is more natural than the Class object and using the normal approach you get back the same zero-length array that you passed in if the collection is of size zero. It does look nice from a "caller" perspective though.

  • A suggestion : use "loop array list" instead of ArrayList / LinkedList

    ArrayList is good at:
    get / set by index : O(1)
    appending : O(log(n))
    remove last : O(1)
    and very bad at:
    add middle : O(n)
    remove from middle : O(n)
    LinkedList is good at:
    fast remove from middle, if your iteraror already goes there : O(1)
    convenient methods : addFirst, addLast, removeFirst, removeLast : O(1)
    and very bad at :
    get / set by index : O(n)
    here I want to make a suggestion : use "loop array list" instead of the ArrayList and LinkedList.
    a "loop array list" is based on array, just like ArrayList. But it has 2 member-variables : the start position, and the real size. the start position can be anywhere within array.length. an element of index "i" is stored in array[ start + i ], and when (start + i > array.length), loop to the beginning of the array; when (start + i < 0), loop to the end of the array.
    this "loop array list" has all the good sides:
    get / set by index : O(1)
    add first / last : O(log(n))
    remove first / last : O(log(n))
    add / remove from middle : O(n)
    (note : because we shrink the backup-array when the real size is too small, add / remove operation take O(log(n)) now.)
    the only problem is : add / remove from middle. let's take a look at it.
    1. the LinkedList does NOT really add/remove from middle in O(1), you has to locate the element, which is O(n).
    2. O(n) is acceptable, O(n^2) is not acceptable. try this : keep removing first element from an very big ArrayList ( size>10^6 ) until it's empty.
    the fact is, any list can perform batch-remove / batch-add operation in O(n) instead of O(n^2). it's easy : allocate a new list, iterate the original list, copy the element into the new list if condition is satisfied.
    so, instead of "remove from middle", what we need is a new methods : removeAllByCondition( Condition condition ), and now the batch-remove operation can be done in O(n)
    here is an implementation of mine. I've tested it on my computer( 512mem + 2G cpu, win2k + jdk1.5 ), it's amazing, just a little slower then ArrayList when add last, and a liitle slower then LinkedList when batch-remove. in all other cases, it's far more better then those 2 kinds of List.
    // source code : List2
    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.NoSuchElementException;
    import java.util.Set;
    public final class List2<T> extends AbstractList<T> {
    private static int initialArrayLength = 4;
    private T[] array;
    private int start;
    private int size;
    private void init( T[] newArray, int start_a, int size_a ) {
    array = newArray;
    start = start_a;
    size = size_a;
    @SuppressWarnings("unchecked")
    private void init() {
    init( (T[]) new Object[ initialArrayLength ], 0, 0 );
    public List2() {
         init();
    @SuppressWarnings("unchecked")
    public List2( Collection<? extends T> collection ) {
         init(
              collection.toArray( (T[]) new Object[ collection.size() * 11 / 10 + 1 ] ),
              0,
              collection.size()
    private List2( T[] array_a, int start_a, int size_a ) {
         init( array_a, start_a, size_a );
    @SuppressWarnings("unchecked")
    public static <TT> List2<TT> createV( TT... elements ) {
         TT[] array = (TT[]) new Object[ elements.length * 11 / 10 + 1 ];
         System.arraycopy( elements, 0, array, 0, elements.length );
         return new List2<TT>( array, 0, elements.length );
    public static List2<Double> create( double... elements ) {
         Double[] array = new Double[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array[i] = elements;
         return new List2<Double>( array, 0, elements.length );
    public static List2<Integer> create( int... elements ) {
         Integer[] array2 = new Integer[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Integer>( array2, 0, elements.length );
    public static List2<Character> create( char... elements ) {
         Character[] array2 = new Character[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Character>( array2, 0, elements.length );
    public static List2<Character> create( String s ) {
         return create( s.toCharArray() );
    public List2<T> clone() {
         return new List2<T>( this );
    // basic
    public int size() {
         return size;
    private int index( int index ) {
         int i = start + index;
         if( i >= array.length )
              i -= array.length;
         return i;
    public T get( int d ) {
         if( d < 0 || d >= size )
              throw new IndexOutOfBoundsException();
         if( size == 0 )
              throw new NoSuchElementException();
         return array[ index( d ) ];
    public T set( int index, T element ) {
         if( index < 0 || index >= size )
              throw new IndexOutOfBoundsException();
         int i = index( index );
         T oldElement = array[i];
         array[i] = element;
         return oldElement;
    @SuppressWarnings("unchecked")
    private void copyAndSetToNewArray( int newArrayLength ) {
         T[] newArray = (T[]) new Object[ newArrayLength ];
         for( int i=0; i<size; i++ )
              newArray[i] = array[ index( i ) ];
         init( newArray, 0, size );
    public void addFirst( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         int i = index( array.length - 1 );
         array[ i ] = element;
         start = i;
         size++;
    public void addLast( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         array[ index( size ) ] = element;
         size++;
    public T removeFirst() {
         if( size == 0 )
              throw new NoSuchElementException();
         T oldElement = array[ start ];
         array[ start ] = null;
         start = index( 1 );
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    public T removeLast() {
         if( size == 0 )
              throw new NoSuchElementException();
         int i = index( size - 1 );
         T oldElement = array[i];
         array[i] = null;
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    @SuppressWarnings("unchecked")
    public int removeAll( ListCondition<T> condition ) {
         T[] newArray = (T[]) new Object[ array.length ];
         int iNew = 0;
         for( int i=0; i < size; i++ ) {
              T element = get( i );
              if( ! condition.isConditionSatisfied( this, i, element ) )
                   newArray[ iNew++ ] = element;
         int oldSize = size;
         init( newArray, 0, iNew );
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return size - oldSize;
    // aux
    public boolean equals(Object obj) {
         if( obj == this )
         return true;
         if( obj instanceof List2 ) {
              List2 that = (List2) obj;
              if( this.size != that.size )
                   return false;
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], that.array[ that.index(i) ] ) )
                        return false;
              return true;
         if( obj instanceof List ) {
              List that = (List) obj;
              if( this.size != that.size() )
                   return false;
              Iterator thatIter = that.iterator();
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], thatIter.next() ) )
                        return false;
              return true;
         return true;
    public int hashCode() {
         int hashCode = 1;
         for( int i=0; i < size; i++ ) {
              T element = array[ index( i ) ];
         hashCode = 31*hashCode + ( element==null ? 0 : element.hashCode() );
         return hashCode;
    public boolean isEmpty() {
         return size == 0;
    public T getFirst() {
         return get( 0 );
    public T getLast() {
         return get( size() - 1 );
    public T getRandom() {
         return get( (int) (Math.random() * size) );
    public int indexOf( Object element ) {
         for( int i=0; i < size; i++ )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public int lastIndexOf( Object element ) {
         for( int i=size-1; i >= 0; i-- )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public boolean contains( Object element ) {
         return indexOf( element ) != -1;
    public boolean add( T element ) {
         addLast( element );
         return true;
    @Deprecated
    public void add( int index, T element ) {
         throw new UnsupportedOperationException();
    public T remove() {
         return removeFirst();
    @Deprecated
    public boolean remove( Object element ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    @Deprecated
    public T remove( int index ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    public void clear() {
         init();
    public Object[] toArray() {
         Object[] result = new Object[ size ];
         for( int i=0; i < size; i++ )
         result[i] = array[ index( i ) ];
         return result;
    @SuppressWarnings("unchecked")
    public <TT> TT[] toArray( TT[] a ) {
    if( a.length < size )
    a = (TT[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size );
    for( int i=0; i < size; i++ )
    a[i] = (TT) array[ index( i ) ];
    if( a.length > size )
         a[size] = null;
    return a;
    @SuppressWarnings("unchecked")
    public void sort() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0; i < size; i++ )
              array[ i ] = (T) a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = (T) a[ j ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sort( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0; i < size; i++ )
              array[ i ] = a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = a[ j ];
         start = 0;
    public String toString( String delimiter ) {
         return toString( "", delimiter, "", size() );
    public String toString( String prefix, String delimiter, String suffix, int max ) {
         StringBuffer stringBuffer = new StringBuffer( prefix );
         int dest = Math.min( max, size );
         for( int i=0; i < dest; i++ ) {
              stringBuffer.append( get(i) );
              if( i < dest - 1 )
                   stringBuffer.append( delimiter );
         if( size > max )
              stringBuffer.append( "...(" ).append( size() - max ).append( " more)" );
         stringBuffer.append( suffix );
         return stringBuffer.toString();
    // batch operation
    public boolean containsAll( Collection<?> that ) {
         Set<Object> thisSet = new HashSet<Object>( this );
         for( Object element : that )
              if( ! thisSet.contains( element ) )
                   return false;
         return true;
    @SuppressWarnings("unchecked")
    public List2<T> subList( int fromIndex, int toIndex ) {
         if( fromIndex < 0 || toIndex > size || toIndex < fromIndex )
              throw new IndexOutOfBoundsException();
         int newSize = toIndex - fromIndex;
         T[] newArray = (T[]) new Object[ newSize * 11 / 10 + 1 ];
         for( int i=fromIndex, iNew=0; i < toIndex; i++, iNew++ )
              newArray[ iNew ] = array[ index( i ) ];
         return new List2<T>( newArray, 0, newSize );
    public void addV( T... that ) {
         for( T element : that )
              addLast( element );
    public boolean addAll( Collection<? extends T> that ) {
         for( T element : that )
              addLast( element );
         return ! that.isEmpty();
    @Deprecated
    public boolean addAll( int index, Collection<? extends T> c ) {
         throw new UnsupportedOperationException();
    public void removeRest( T element ) {
         int position = lastIndexOf( element );
         if( position == -1 )
              return;
         while( ! Tools.equals( element, removeLast() ) );
    public void removeAllEquals( final T element ) {
         removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T currentElement) {
              return currentElement.equals( element );
    public void removeAllBetween( final T from, final T to ) {
         removeAll( new ListCondition<T>() {
              @SuppressWarnings("unchecked")
              public boolean isConditionSatisfied(List2 list, int index, T element) {
                   if( from != null && ((Comparable) from).compareTo( element ) > 0 )
                        return false;
                   if( to != null && ((Comparable) to).compareTo( element ) <= 0 )
                        return false;
                   return true;
    public boolean retainAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return ! thatSet.contains( element );
         return removeCount > 0;
    public boolean removeAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return thatSet.contains( element );
         return removeCount > 0;
    // unit test
    private static int maxTestCount = 1000 * 1000;
    public static void unitTest() throws Exception {
         // thest thoese methods for one time
         Tools.ensureEquals( new List2(), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), List2.create( "abcdef" ) );
         final List<Double> list1 = new ArrayList<Double>();
         final List2<Double> list2 = new List2<Double>();
         Runnable[] tasks = new Runnable[] {
              // test those methods that do NOT change the list
              new Runnable() { public void run() {
                   Tools.ensureEquals( new List2<Double>( list1 ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray() ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray( new Double[0] ) ), list1 );
                   double[] doubles = new double[ list1.size() ];
                   int i = 0;
                   for( double d : list1 )
                        doubles[i++] = d;
                   Tools.ensureEquals( List2.create( doubles ), list1 );
                   Tools.ensure( list1.isEmpty() == list2.isEmpty() );
                   Arrays.equals( list1.toArray(), list2.toArray() );
                   Tools.ensureEquals( list1, list2.clone() );
                   Double notExistElement = -2.0;
                   Tools.ensure( list1.indexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.lastIndexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.contains( notExistElement ) == false );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.hashCode(), list2.hashCode() );
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.get(0).equals( list2.getFirst() ) );
                   Tools.ensure( list1.get(list1.size()-1).equals( list2.getLast() ) );
                   Double existRandomElement = list2.getRandom();
                   Tools.ensure( list1.contains( existRandomElement ) );
                   Tools.ensure( list2.contains( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   int from = (int) (Math.random() * list1.size());
                   int to = (int) (Math.random() * (list1.size()+1));
                   if( from > to ) {
                        int t = from;
                        from = to;
                        to = t;
                   Tools.ensureEquals( list1.subList( from, to ), list2.subList( from, to ) );
              // test those methods that change the list
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   double d = Math.random();
                   list1.set( i, d );
                   list2.set( i, d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   Tools.ensure( list1.get( i ).equals( list2.get( i ) ) );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( 0, d );
                   list2.addFirst( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( 0 ).equals( list2.removeFirst() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( list1.size() - 1 ).equals( list2.removeLast() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = 0;
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); i++ ) {
                        iter.next();
                        if( i % 3 == 0 )
                             iter.remove();
                   list2.removeAll( new ListCondition<Double>() { public boolean isConditionSatisfied(List2 list, int index, Double element) {
                        return index % 3 == 0;
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.add( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove(0).equals( list2.remove() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int r = (int) (Math.random() * list1.size());
                   Double element = list1.get( r );
                   int index = list1.lastIndexOf( element );
                   for( int i=list1.size()-1; i>=index; i-- )
                        list1.remove( i );
                   list2.removeRest( element );
              new Runnable() { public void run() {
                   list2.removeRest( Math.random() - 2 );
              new Runnable() { public void run() {
                   list1.clear();
                   list2.clear();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   list2.sort();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   Collections.reverse( list1 );
                   list2.sortDesc();
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   list2.sort( comparator );
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   Collections.reverse( list1 );
                   list2.sortDesc( comparator );
              new Runnable() { public void run() {
                   Double notExistElement = -2.0;
                   list2.removeAllEquals( notExistElement );
                   Tools.ensureEquals( list1, list2 );
                   list2.removeAllBetween( 0.5, 0.6 );
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); ) {
                        double d = iter.next();
                        if( d >= 0.5 && d < 0.6 )
                             iter.remove();
                   Tools.ensureEquals( list1, list2 );
         System.out.print( "test List2 " );
         for( int i=0; i < maxTestCount; i++ ) {
              tasks[ (int) (Math.random() * tasks.length) ].run();
              Tools.ensureEquals( list1, list2 );
              if( i % (maxTestCount/10) == 0 )
                   System.out.print( "." );
         System.out.println( " ok" );
    // source code : ListCondition
    public interface ListCondition<T> {
    boolean isConditionSatisfied( List2 list, int index, T element );

    Hi,
    I have the following statement:
    private List list = new ArrayList();
    why not use private ArrayList list = new
    ArrayList()?
    I know ArrayList implements List, so list has a wide
    scope, right? What's the benefit?
    Thanks,
    JieBy using the interface you are not tied to a specific implementation.
    Later, you may determine that using a LinkedList is more efficient to your specific code and then all you need to do is change the statement to:
    private List list = new LinkedList();As long as you are not casting the list reference to ArrayList (or something along those lines) you would not need to change anything else.

  • Private static ArrayList within java.util.Arrays

    I was recently reviewing the code in java.util.Arrays (class version 1.45 - Java version 1.4.1). Beginning on line 2289 is a private static class named ArrayList. I'm completely baffled as to why the author created this slimmed-down private class (which would be, incidentally, returned by the Arrays.asList(Object[] a) method) rather than use the public class java.util.ArrayList. Can anyone offer an explanation?
    Thanks,
    John

    from JDK JAVADoc:
    asList
    public static List asList(Object[] a)
    Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray. The returned list is serializable.
    So the private ArrayList extends java.util.ArrayList, and any changes made this list does not affect the internal Object[].... in other words can not be changed.

  • Howto implement toArray from Collections E

    Hi!
    I am trying to implement the generic Collection<E> interface and the toArray method is giving me trouble. Imitating the code from LinkedList, I can do this:
    public class Test<E> implements Collection<E> {
        protected E elt;
        public Test() {}
        public Test(E elt) {
            this.elt = elt;
        public <T> T[] toArray(T[] a) {
            if (a.length == 0) {
                a = (T[]) java.lang.reflect.Array.newInstance(
                        a.getClass().getComponentType(), 1); // generates unchecked warning
            Object[] ret = a;
            ret[0] = elt;
            if (a.length > 1)
                a[1] = null;
            return a;
    }However, this gives me an annoying unchecked warning. Of course, I can simply suppress the warning with @SuppressWarnings("unchecked"), but is there a Right Way of doing this that I am missing?

    Check Angelika Langer's Generics FAQ. But I don't believe there is. There are lots of places where the JDK source code has to ignore type safety and I think this is one of them.

  • Db_dotnet - Compare delegate being collected

    I traced down a problem I am having to the following simple test case. (see code below)
    If we remove the EntryComparisonDelegate from the the secondary database config, everything works fine.
    Otherwise I get either of the following errors:
    CallbackOnCollectedDelegate was detected
    Message: A callback was made on a garbage collected delegate of type 'libdb_dotnet50!BerkeleyDB.Internal.BDB_CompareDelegate::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.
    at this location
         libdb_dotnet50.dll!BerkeleyDB.Internal.DB.put(BerkeleyDB.Internal.DB_TXN txn = null, BerkeleyDB.DatabaseEntry key = {BerkeleyDB.DatabaseEntry}, BerkeleyDB.DatabaseEntry data = {BerkeleyDB.DatabaseEntry}, uint flags = 0) Line 273 + 0x6e bytes     C#or
    System.AccessViolationException was unhandled
    Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
    Source=libdb_dotnet50
    StackTrace:
    at BerkeleyDB.Internal.libdb_csharpPINVOKE.DB_put(HandleRef jarg1, HandleRef jarg2, HandleRef jarg3, HandleRef jarg4, UInt32 jarg5)
    at BerkeleyDB.Internal.DB.put(DB_TXN txn, DatabaseEntry key, DatabaseEntry data, UInt32 flags) in Z:\db-5.0.26\csharp\Internal\DB.cs:line 273
    at BerkeleyDB.Database.Put(DatabaseEntry key, DatabaseEntry data, Transaction txn, UInt32 flags) in Z:\db-5.0.26\csharp\Database.cs:line 650
    at BerkeleyDB.Database.Put(DatabaseEntry key, DatabaseEntry data, Transaction txn) in Z:\db-5.0.26\csharp\Database.cs:line 595
    at BerkeleyDB.Database.Put(DatabaseEntry key, DatabaseEntry data) in Z:\db-5.0.26\csharp\Database.cs:line 576
    at ConsoleApplication1.Program.Main(String[] args) in c:\users\administrator\documents\visual studio 10\Projects\ConsoleApplication10\ConsoleApplication1\Program.cs:line 44
    at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()
    InnerException:
    class Program
              static DatabaseEntry keyGen(DatabaseEntry k, DatabaseEntry d)
                   return new DatabaseEntry(new byte[] { 1, 2, 3, 4 });
              static int comp(DatabaseEntry k1, DatabaseEntry k2)
                   return 0;
              static void Main(string[] args)
                   if (File.Exists("data.db")) File.Delete("data.db");
                   Database db = BTreeDatabase.Open("data.db", "master", new BTreeDatabaseConfig()
                        Creation = CreatePolicy.IF_NEEDED
                   SecondaryDatabase sdb = SecondaryBTreeDatabase.Open("data.db", "index", new SecondaryBTreeDatabaseConfig(db, keyGen)
                        Creation = CreatePolicy.IF_NEEDED,
                        Duplicates = DuplicatesPolicy.SORTED,
                        Compare = comp
                   for (int i = 0; i < 100; i++)
                        byte[] b = BitConverter.GetBytes(i).Reverse().ToArray();
                        db.Put(new DatabaseEntry(b), new DatabaseEntry(b));
    GC.Collect();
                   sdb.Close();
                   db.Close();
    I am using
    db-5.0.26
    visual studio 2010 / .net 4.0
    windows 2008 server
    Any ideas on what I am doing wrong?

    Hello,
    Thank you for reporting this issue. We are aware of the problem and it is currently
    being tracked internally as #18935.
    Thanks again,
    Sandra

  • Should Collections be used as return types across threads?

    I am wondering when, if ever, it is appropriate to use a Collection as the return type of a method in a multi-threaded environment. Here is our situation:
    We have four classes -- Widget, WidgetManager, ClientA, and ClientB. ClientA and ClientB are running in different Threads from each other and from the WidgetManager.
    The WidgetManager class that uses a Collection of Widgets internally, and passes the Collection (or an Iterator over it) out as a return value of a method to ClientA, which is running in another thread. ClientA would start to go through it using next() and hasNext() of the Iterator. If the WidgetManager were to get a request from ClientB running in another thread to eliminate a Widget, it would attempt to remove it from the Collection. If ClientA were still looping through the Iterator, this would throw an IllegalStateException b/c the system would be in an inconsistent state. The Iterator given to the ClientA is directly linked to the actual Collection in the WidgetManager (am I right so far?).
    In my opinion, in most cases we don't want to synchronize Collections. In the example above, if we had passed out a synchronized Collection, then the WidgetManager couldn't touch the collection while the client was looping through the Iterator. If the client got hung up while looping, then the WidgetManager would be hung up. In this case, I think that it will be better to use the toArray() method of Collection to just dump out the contents to a plain array of Objects. Actually, the WidgetManager could convert this array of Objects to an array of Widgets before passing it out, which would give us the type checking that we don't get with Containers.
    The condition where you would want to use a synchronized Collection would be when you actually want the client to do some writing or removing from the Collection. I would expect this to be pretty rare since you usually dont want to give clients access to an interal member (the Collection) of a class.
    I think that it is also possible to have read-only Collections, but I think (don't know for sure) that you would still have the same IllegalStateException or synchronization probelms.
    Can someone point out the errors in my thinking? Or should you generally only use Collections as internal members in a multi-threaded environment, and use toArray() whenever you want to pass the Collection's data outside of the class?
    Thanks for any help.
    Keith

    I haven't tested what happens when you synchronize the
    Collection, but I think that you are right. But this
    causes the problem that I mentioned in the first post.
    That is, what happens if your client STARTS running
    through the Iterator, and then stops or gets hung up
    for some reason? I assume that you're still blocked.
    And it's pretty important to me in this case to not
    t be blocked -- WidgetManager is the highest level
    class in the system.
    I'd like to know if anyone has tested this.
    The Iterator implementations used in java.util do not use any synchronization by itself, (which is what you would expect since synchronization over multiple method call will involve much more complications and slower performance) . With iterator, you have to provide the necessary synchronization yourself to maintain thread-safety like this
    Iterator itr = get Iterator from collectionInstance ;
    synchronized(collectionInstance) {
    while(itr.hasNext())
    process itr.next() ...
    As long as your client code gracefully exits the synchronized block on a stop( or hangup, given that it is detected and handled fast enough), it will not be a problem.
    Also, I'd like an example of when you WOULD want to
    return a Collection. I'm specifically interested in
    when you would want to return one in a multi-threaded
    environment, but I'm beginning to wonder when you
    would EVER want to return one from a method.
    Collections are great for internal uses, but you lose
    type-checking and you expose the internals of your
    class to modification when you use them as return
    types. And if you're returning a read-only
    Collection, you might as well return an array, right?Using a read-only proxy will be much faster and space-efficient than toArray().

  • How do I modify an Array into a collection

    Hi I'm havin a real hard time modifying an Array into a collection, heres the code I'm working with
    I have to modify all the Arrays of this code....
    public class Student {
         private String           name;
         private float []      grades;
         private int           finalGrade;
         public Student(String name) {
              this.name      = name;
              this.grades = new float[5];
              for (int i = 0; i < grades.length; i ++) {
                   grades[i] = 0.0f;
              finalGrade = 0;
         public String toString() {
              String studentInfo = " Grades for " + name + ": ";
         for (int i = 0; i < grades.length; i ++)
         studentInfo += " " + grades;
         studentInfo += "\n final grade: " + getFinalGrade();
         return studentInfo;
         private void setFinalGrade() {
              float temp = 0.0f;
              for(int i = 0; i < grades.length; i++)
                   temp += grades[i];
              finalGrade = Math.round(temp/grades.length);
         public int getFinalGrade() {
              this.setFinalGrade();
              return finalGrade;
         public void setGrade( int index, float grade) {
              this.grades[index] = grade;
         public float[] getGrades() {
              return grades;
         public String getName() {
              return name;

    I'm kind of new at this I just started to learn about
    that, is there an example u could give me to inspire
    me ?
    Object[] o = new String[]{"one", "two", "five"};
    Collection ascollection = Arrays.asList(o);
    //the returned Collection (List) is unmodifiable,
    //so if we want to remove or add items, we need
    //a copy:
    Collection copy = new ArrayList(ascollection);
    copy.remove("two");
    String[] backagain = (String[]) copy.toArray(new String[copy.size()]);

  • In need of help with Collections.

    Greetings,
    I've been assigned a college work where I have to develop a solution, utilizing Swing and Collections, to the problem below:
    "There is a department store with several products. The store owner doesn't know exactly how many product types there are, so he decided to register all types of products. The registering option consists of the following operations: add, remove, and change product.
    The products have three characteristics (attributes): name, quantity and price. Once all products are registered, the store owned wants to see a list of the products in alphabetical order on the screen.
    The store owner also wants the program to sell the products. The sale is done with the user searching for a product by the name, and the program will show the price of the product on the screen. The user confirms that it's the right product, and the program will reduce the item's quantity by one.
    Obs.: To simplify the problem, work with a reduced number of products. Also the program does not need to store date in the disk."
    So far I've built a class named Product, a visual class for the GUI and the main class. Inside the Product class I have a String for the name, a Float for the price, and Integer for the quantity, as well as the getters and setters for those private variables.
    In the GUI class I've made a Product Array and I also made the text fields so the user can type the data and put it in the array. This part seems to be working fine. The problem begins when using Collections. How can I use this array to make a sorted list of the products (it seemed to work when using Arrays.sort(products, byAlpha [Comparator I've creadted to sort alphabetically]), but I don't know how to work with this, now supposedly sorted, data), maybe put it inside a JList, where the user can see what products he is registering in real time? Can I make it so the user clicks on the product in the JList and he can now delete it or change the values of that product (price, quantity)?
    Any help, suggestions, insight, are greatly appreciated. Thanks in advance!
    Thiago.

    So, for example, on a JButton, I should
    write the code on a different class, and in the GUI
    class, make an instance of that class (or is it the
    other way around?), and call the method that I need
    for that button inside the actionPerformed? (Sorry if
    I sound confusing, I'm not very familiar with Java)Suppose you have a class called Store, that represents the store. Internally, it has a Collection of Products, but the caller doesn't need to know that.
    So, Store might have a method called findProducts:
    public Collection<Product> findProducts(String findThis) {
        Collection<Product> returnThis = new ArrayList<Product>;
        // code here that searches through the internal collection, and
        // adds products whose names match the search string to returnThis
        return returnThis;
    }So then you might have a GUI that looks like this:
    public class StoreGUI {
        private Store theStore;
        public StoreGUI() {
            theStore = new Store();
            // create frame, etc.
            final JTextField searchThis = new JTextField();
            JButton searchButton = new JButton("Search");
            final JList searchResults = new JList();
            searchButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    Collection<Product> result = store.findProducts(searchThis.getText());
                    searchResults.setListData(result.toArray());
            // add text field, button, etc. to frame, etc.
    It may be preferable to get rid of getters and
    setters and instead have operations that are
    specifically meaningful for Products. Not sure if I understand, could you give me an
    example of how I could do that?I mean that if Product now has this:
    private int quantity;
    public int getQuantity() {
        return quantity;
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }Then arguably that doesn't make sense, because when you run a store you can't just magically create a hundred boxes of cornflakes, which (arguably) is what you'd be doing if you did this:
    cornflakes.setQuantity(100);So it might make more sense to get rid of setQuantity, and provide methods on Product like this:
    private int quantity;
    public int getQuantity() { // this is still OK, you can always look at your inventory
        return quantity;
    public void buy(int quantity) {
        // check to make certain that quantity is no more than this.quantity
        this.quantity -= quantity;
    public void addInventory(int quantity) {
        this.quantity += quantity;
    }This might not be the best example, because the difference isn't huge. But the idea is that you're modelling reality a little more closely, and you're moving the logic that controls the state of the object, directly into the logic. (So you don't have some external object calling getQuantity, changing it, and then calling setQuantity.) This tends to make code easier to maintain.
    The book I'm using as reference gives examples
    of List and ArrayList, but only using String. I'm not
    sure how to use it for my Product class, would it be
    something like this?
    > HashSet<Product> products = new HashSet<Product>();Yes, that's exactly right.
    Also, do you happen to know any
    resource on the web where I can learn more about
    Collections?http://java.sun.com/docs/books/tutorial/collections/index.html

  • Implementation of toArray(Object[] a)

    I'm having trouble grasping one small aspect of the method, specifically:
    "Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection."
    As I understand it, if a user passes in an array of String objects and the array is not long enough, I need to allocate a new array of String objects, and not just simply an array of Objects. How exactly would I go about instantiating an array of objects of a specific type that is determined at runtime?

    You can look in the src.zip to see how this is done for ArrayList:
    public Object[] toArray(Object a[]) {
        if (a.length < size)
            a = (Object[])java.lang.reflect.Array.newInstance(
                                    a.getClass().getComponentType(), size);
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
             a[size] = null;
        return a;
    }

  • Can anyone clarify me about the api Object[] toArray(Object[])

    There are two apis in Collections framework to convert the Collection elements into an array
    1. Object[] toArray()
    2. Object[] toArray(Object[])
    Can some one explain me what does the second api - Object[] toArray(Object[]) does ?

    Just read the javadoc API of the Collection interface: toArray() just returns an Object[]. But if you need for example a String[] as result use
    String[] sa = o.toArray(new String[0]);

Maybe you are looking for

  • Need solution for a Reporting Requirement

    Hello Experts, I need design a solution for Report, where in I need to show ageing of Invoice based of Due date of Invoice for last four weeks as explained below: In cube i have records like this: Industry       Invoice Number      Due Date      Amou

  • Unicode error in business object ECC6

    Hi all, We upgraded from 4.6c to ECC6. While executing a business object we got the syntax following error in ECC6. The program "Z_2005PP" is not Unicode-compatible, according to its program attributes We dont know how to solve it, becauseZ_2005PP is

  • Database objects behind stats on "Concurrent Processing Dashboard" ?

    I want to define a new report in oem grid about concurrent processing on a ebs target. i saw that there is some minimal stats in the 'Concurrent Processing Dashboard'. What are the DB tables used to generate this screen ? By the way there is a bug, a

  • Problems installing PE 4.0 in Mac, Mountain Lion

    Since I have CS 4 running on my McBook (Snow Leopard) I don't need PE 4.0 anymore. I wanted to install Photoshop Elements 4.0 on my new Mac (Mountain Lion). When I tried, it ran through all of the necessary installation steps with one exception. I wa

  • Should n't there be a separate forum for JDev 10g and another for 11g?

    Dear experts, Since there are still long and ongoing projects using JDev 10g, it would be convenient to split this forum into two , so that searches would be faster and finding the right solution for the correct version of JDev would be easier and qu