Warning in java : unchecked or unsafe operation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hostel
    New Member
    • Feb 2007
    • 17

    #1

    Warning in java : unchecked or unsafe operation

    import java.util.Array List;
    import java.util.Itera tor;


    public class collectionsremo ve
    {

    public static void main(String[] args)
    {


    ArrayList arr = new ArrayList();
    String str1 = "hi";
    arr.add(str1);
    arr.add("hello" );
    arr.add("wassup ");
    arr.add("wazzup ");
    arr.add("bye");



    Iterator it = arr.iterator();

    while(it.hasNex t() )
    {

    it.next();
    it.remove();
    }
    }
    }

    }



    when i compile this code i get warning as :
    collectionsremo ve.java use unchecked or unsafe operation
    recompile with -Xlint : unchecked for detail


    how to remove this warning .

    anyhow my program runs fine , how to remove
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Starting at Java 1.5 the Java language implements 'generics', i.e. a type can be
    specified using another type. This is all a compilation feature and the Java virtual
    machine didn't change for that. You are using the 'raw' type of ArrayList and the
    compiler warns you for it (you can stick any type on a raw List). After compilation
    has finished the 'type erasure' mechanism sets in; it doesn't do anything, it just
    uses the raw type where you had specified a generic type.
    This is how you define a List that stores Strings:

    [code=java]
    List<String> list= new ArrayList<Strin g>();
    [/code]

    You can use that 'list' to store and remove Strings in/from it and the compiler will
    keep its mouth shut. If you want to store a different type in your list the compiler
    will heavily complain to you.

    kind regards,

    Jos

    Comment

    • BigDaddyLH
      Recognized Expert Top Contributor
      • Dec 2007
      • 1216

      #3
      Here are two tutorials you may find useful:

      Collections tutorial (using generics)

      Generics tutorial

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Also have a look at this Wikipedia page. It has some fine external references.

        kind regards,

        Jos

        Comment

        Working...