Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

typesafety: parameterization of arraylist[]

807605Jul 15 2007 — edited Jul 15 2007
hello everybody!

i have this code snippet:
package my_package;

import java.util.ArrayList;
import java.util.Collections;

public class TypeSafety
{
   public static void main(String[] args)
   {
      int size = 5;
      ArrayList[] db = new ArrayList[size];
      
      for (ArrayList my_db:db)
      {
         my_db = new ArrayList<String>();
         my_db.add("foo");
         
         Collections.sort(my_db);
      }
   }
}
where i get a warning on the calls add() and sort(). (i use eclipse 3.2 to code)
the warning on add() says: Type safety: The method add(Object) belongs to the raw type ArrayList.
References to generic type ArrayList<E> should be parameterized

so i tried to replace
ArrayList[] db = new ArrayList[size];
with
ArrayList<String>[] db = new ArrayList<String>[size];
but then i get the error Cannot create a generic array of ArrayList<String>. i find this quite confusing. didn't the warning tell me to to exactly that?

the second warning says Type safety: Unchecked invocation sort(List) of the generic method sort
(List<T>) of type Collections
. here i simply do not know what i could try.

if i substitute the array with a arraylist i can use generics and the warnings go away.
package my_package;

import java.util.ArrayList;
import java.util.Collections;

public class TypeSafety
{
   public static void main(String[] args)
   {
      int size = 5;
      ArrayList<ArrayList> db = new ArrayList<ArrayList>(size);
      
      for (int i = 0; i < db.size(); i++)
      {
         ArrayList<String> subList = new ArrayList<String>();
         subList.add("foo");
         Collections.sort(subList);
         
         db.add(subList);
      }
   }
}
but i would like to know if it's possible to do it (without warnings) with an array.

thanks for your help in advance and
kind regards

--alex
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 12 2007
Added on Jul 15 2007
11 comments
327 views