Question:
How to prevent this warning that I get in java?
Love_To_Learn
2011-03-19 06:46:23 UTC
here is the code:

import java.util.*;
class Idiot
{
public static void main(String args[])
{
List list=new ArrayList();
list.add(0,new Integer(4));
}
}
and here is the warning that I get when I compile it.

Note: list.java uses unchecked or unsafe operation
Note: Recompile with -Xlint:unchecked for details.

How to prevent this warning without using Generics?
Three answers:
ironvital
2011-03-19 06:57:38 UTC
I think, there is really no way to prevent it without using Generics.

This warning indicates that your ArrayList could potentially include instances of different types (different objects)



If you intend your ArrayList to store integers, use the following code.

List list = new ArrayList();



If you don't like Generics for some reason, don't use them, just make sure to not include different objects in the same List.
Silent
2011-03-19 13:56:27 UTC
You really should be using generics. That's the right way to do this. Why don't you want to? If it's just because you don't know how they work, that's not a good reason.



If you really must do it without generics for some reason, and you actually care about the warning (warnings don't stop the code from compiling) you can add an annotation before the method to suppress the warning:



@SuppressWarnings("unchecked")



This is almost certainly the wrong thing to do.
tristan c
2011-03-19 14:01:59 UTC
The way you are using the array list is not type safe. The safe way to do this is to specify exactly what type you are storing in the list using the generic ArrayList class:



ArrayList list = new ArrayList();



The angular parenthesis are used to specify the type.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...