Unchecked conversion

Hi all,
I have a Swing application that uses few generic classes. Currently I'm trying to remove all warnings in my code (adding serialVersionUID is very annoying by the way). I want to express one of my problem with a basic sample.
Consider that I define a generic class A:
public class A<T> {
     public List<String> getList() {
          return new ArrayList<String>();
}And another class B that uses A:
public class B {
     public void doSomethingUnsecure(A a) {
          List<String> list = a.getList();
          for(String item : list) {
               System.out.println(item);
     public void doSomethingSecure(A a) {          
          for(Object o : a.getList()) {
               String item = (String)o;               
               System.out.println(item);
}I have a few question regarding this piece of code:
1) Why 'List<String> list = a.getList();' in 'doSomethingUnsecure' gives a warning ? It's not the case if A is not generic.
The warning is "Type safety: The expression of type List needs unchecked conversion to conform to List<String>"
2) Why I get no warning at all for 'doSomethingSecure' ?
3) Is there a better way to go around this problem than casting each element in the list (like in doSomethingSecure) ?

>
public class A<T> {
     public List<String> getList() {
          return new ArrayList<String>();
public class B {
     public void doSomethingUnsecure(A a) {
          List<String> list = a.getList();
          for(String item : list) {
               System.out.println(item);
     public void doSomethingSecure(A a) {          
          for(Object o : a.getList()) {
               String item = (String)o;               
               System.out.println(item);
}1) Why 'List<String> list = a.getList();' in 'doSomethingUnsecure' gives a warning ? It's not the case if A is not generic.Because once you declare A<T>, java is going to generate a warning every time you use A without some kind of <> after it.
A generic type is forever generic. Using the "raw" type is permissible, and sometimes even necessary, but it always gets a warning.
You want to tell it A<SomeClass>, and you want to try and make sure that your <SomeClass> is correct. If you can't, then you might be able to get away with using A<?>, as suggested, if you are treating the A<> item as read-only.
2) Why I get no warning at all for 'doSomethingSecure' ?Because anything can fit into a variable of type Object, so iterating with "Object o" is okay. No cast is needed in this case.
3) Is there a better way to go around this problem than casting each element in the list (like in doSomethingSecure) ?Get the type parameters right, as mentioned above.
=Austin

Similar Messages

  • Warning: [unchecked] unchecked conversion.. how to avoid this warning?

    Hi all,
    When i compile my java file, i get this warning.
    Z:\webapps\I2SG_P2\WEB-INF\classes\com\i2sg>javac testwincDB.java
    Note: testwincDB.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    Z:\webapps\I2SG_P2\WEB-INF\classes\com\i2sg>javac -Xlint testwincDB.java
    testwincDB.java:15: warning: [unchecked] unchecked conversion
    found   : java.util.ArrayList
    required: java.util.ArrayList<java.lang.String[]>
        ArrayList <String[] > recRep2 = dbh.getReconReport2(projID);My functions are:
    public ArrayList getReconReport2(int projID)
            ArrayList <String[] > recRep2 = new ArrayList <String[] > ();
            String getReconReportQuery2 = "select recon_count FROM i2sg_recon1 WHERE PROJECT_ID = " + projID;
            int i=0;
            try {
            resultSet = statement.executeQuery(getReconReportQuery2);
                  while (resultSet.next())
                         recRep2.add(new String[1]); // 0:RECON_COUNT
                ((String []) recRep2.get(i))[0] = resultSet.getString("RECON_COUNT");
                         i++;
                  resultSet.close();
                  } catch (Exception ex)
                ex.printStackTrace(System.out);
            return recRep2;
        }and
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.*;
    public class testwincDB
        public static void main(String args[])
        int projID=8;
        wincDB dbh = new wincDB();
        ArrayList <String[] > recRep2 = dbh.getReconReport2(projID);
        int totalRec = recRep2.size();
         for(int i=0;i<totalRec;i++)
        System.out.println(((String []) recRep2.get(i))[0]);
    }Thanks in advance,
    Lakshma

    found : java.util.ArrayList
    required: java.util.ArrayList<java.lang.String[]>
    ArrayList <String[] > recRep2 = dbh.getReconReport2(projID);This tells all about the warning.....
    public ArrayList getReconReport2(int projID)change it to:
    public ArrayList<String[]> getReconReport2(int projID)Thanks!
    Edit: Very late.... :-)
    Edited by: T.B.M on Jan 15, 2009 7:20 PM

  • Unchecked conversion Warnings!!

    1. how do i get rid of these unchecked conversion warning for
    List<Element> children = new ArrayList<Element>(element.getChildren( "result" ));
    where element.getChildren( "result" ) returns a list of Elements.
    warning is :
    warning: [unchecked] unchecked conversion
    found : java.util.List
    required: java.util.Collection<? extends org.jdom.Element>
    List<Element> children = new ArrayList<Element>(element.getChildren( "result"
    2. warning: [deprecation] setIndent(java.lang.String) in org.jdom.output.XMLOutputter has been deprecated
    output.setIndent(" ");

    1. The message is correct, your code is not safe
    The problem is that getChildren returns List not List<Element>. Do you understand the diference? how can a List of an especified type (Element) be created on a List that accepts everything?
    This will solve your problem:
    //most obvious way to do it
    List<Element> children = new ArrayList<Element>();
    for (Iterator i = element.getChildren( "result" ).iterator(); i.hasNext();){
        children.add((Element) i.next()); //may throw class cast exception
    }Do you get the comment about class cast exception? I sugest reading the Generics Tutorial that comes with the jdk documentation.
    2 The method is deprecated, this means it is there but not supported (This is the java way : -) Go to the API for the reason...
    I did that for you and the method does not even exist anymore, try updating to version 1.0 .

  • Help with "unchecked conversion" warning

    Hello,
    following line
    Vector devices = SomeDeviceManager.getDeviceList();
    gives a warning (when compiled in java 1.5 with -Xlint):
    found raw type: java.util.Vector
    missing type parameters for generic class java.util.Vector<E>
    When I change code to
    Vector<DeviceInfo> devices = SomeDeviceManager.getDeviceList();
    warning turns into "unchecked conversion" warning. SomeDeviceManager is from some old .jar library, so it's not possible to change getDeviceList signature.
    How can I eliminate this warning?
    Thanks.

    @SuppressWarnings("unchecked")
    - Saish

  • Unchecked conversion warning - What is the proper way to fix this?

    I've been trying to figure this out for awhile now, and I have not seen an example that will set me on the right track. Given the following code:
            public TreeSet<String> sort = new TreeSet<String>(CI_NE_Comparator);
            public static Comparator CI_NE_Comparator = new CaseInsensitiveNeverEqualsComparator();
            public static class CaseInsensitiveNeverEqualsComparator implements Comparator
              public int compare(Object o1, Object o2)
                   String s1 = (String) o1;
                   String s2 = (String) o2;
                   int compare = s1.trim().toLowerCase().compareTo(s2.trim().toLowerCase());
                   if (compare == 0)
                        return 1; // ensure like values are never deemed equal
                   return compare;
         }I'm getting a warning declaring the class variable sort:
    Type safety: The expression of type Comparator needs unchecked conversion to conform to Comparator <? super String>
    So just what is the proper method to make the Comparator conform to generics?
    ** Btw - if anyone knows of a better way to do that comparator, I'm all ears!

    Why don't you want like values to be deemed equal?
    What would be wrong with using
    String.CASE_INSENSITIVE_ORDER?The code you see above is a stripped down example. We have the need to present data records in alphabetical order to a user, and sometimes these records have the same dscr, but that doesn't necessarily mean it's a unique record. Because of the backing query, I can't rely on the order in which the records were received.
    I can't modify the queries. Also, I can't modify the 30 or so different types of data records, all having the common field dscr, so that I can write a better implementation. But, I can write a better comparator.
    This is all legacy code that I've been working with, so I have to make sure things work as they did before.

  • Generics with JAXB and Unchecked Conversions

    If there is a more appropriate forum for JAXB related posts, my apologies, I browsed the list and didn't see one.
    Here's my schema:
         </complexType>
         <element name="songList"
              type="com:songListType"/>
         <complexType name="songListType">
              <sequence>
                   <element name="songList"
                        type="string" minOccurs="0" maxOccurs="unbounded"/>
              </sequence>
         </complexType>And my question os
    Is there a way to get JAXB to generate a class that has a method lie
    List<String> getSongList();Instead of
    List getSongList();I'd like to eliminate the unchecked conversions. If anyone has any suggestions or can reference a tutorial, I'd greatly appreciate some tips.
    Thanks

    Wow, sorry for all the typos btw

  • Working around unchecked conversions when using reflection

    I think I've convinced myself that there's no way around this issue when using reflection and Generics, but here's the issue:
    Suppose I've got a method that uses reflection to compare an arbitrary property in
    an arbitrary pair of beans (of the same class).
    public static <T> int compare(T bean0, T bean1, String prop) throws Exception {
         Method m = bean0.getClass().getMethod(
                   "get" + prop.substring(0,1).toUpperCase() +
                   prop.substring(1));
         Object o0 = m.invoke(bean0);
         Object o1 = m.invoke(bean1);
         if (o0 instanceof Comparable &&
             o1 instanceof Comparable &&
             (o1.getClass().isAssignableFrom(o0.getClass()) ||
              o0.getClass().isAssignableFrom(o1.getClass()))) {
              return ((Comparable)o0).compareTo(o1); // compiler warning
         } else {
              return o0.toString().compareTo(o1.toString());
    }There's no way that, in general, when using reflection to invoke methods, that you can coerce the types to avoid compile-time type safety warnings. I think the above code is guarranteed not to throw a runtime ClassCastException, but there's no way to write the code so that the compiler can guarrantee it. At least that's what I think. Am I wrong?

    Ok it looks like you're dealing with a classloader issue. when you call that method, it is the equivelant of calling
    Class.forName("Box", true, this.getClass().getClassLoader())The exception is thrown when your class's classloader cannot find the class box. try putting 'null' there
    Class.forName("Box", true, null)and it will request the bootstrap classloader to load the class. just make sure you have permission :
    If the loader is null, and a security manager is present, and the caller's class loader is not null, then this method calls the security manager's checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it's ok to access the bootstrap class loader. (copied from the API)

  • Unchecked conversion found

    Hi this issue involves two classes.
    in my first class I declare sonarData by doing the following:
    private ArrayList<SonarData> sonarDataArray = new ArrayList<SonarData>();
    further down in my code I call on a method from another class:
    sonarDataArray = fp.parseFiles();
    fp.parseFiles() returns an array list which i declared the same way as the first one:
    private ArrayList<SonarData> sonarDataArray = new ArrayList<SonarData>();
    The issue happens with fp.parseFiles(). It recognizes this as just an ArrayList not an ArrayList<SonarData>
    Hope this makes sense, thanks for any help

    It ArrayList is declared as:
    private ArrayList<SonarData> sonarDataArray = new ArrayList<SonarData>();
    And the method returns sonarDataArray so it should be ArrayList<SonarData> however when I compile it says found ArrayList looking for ArrayList<SonarData>

  • Help in:  uses unchecked or unsafe operations. warnings problem

    need help in my assignment in these warnings problem, i tried it in different ways, one method lists from 0 to end where other should remove or add elements what is listed already,
    public  ArrayList collectModulos(int a){ // no warning in this method
            int [] tmp=new int[10];
            ArrayList <Integer> alst= new ArrayList<Integer>();       
            int i=1; 
            int k=a%i;
            while(i<tmp.length){
                if(a%i==0){               
                    alst.add(i);               
                }i++;          
            } alst.add(0,0);
            return alst;
        public ArrayList removeZero(int a){// warning in this method
            ArrayList <Integer> arl= new ArrayList<Integer>();
            arl=new ArrayList<Integer>(collectModulos(a).subList(1,collectModulos(a).size()));
            return arl;
        public static void main(String[] args){
            Modulos md=new Modulos();
            System.out.println(md.collectModulos(49)+"  "+md.removeZero(49));Modulos.java:36: warning: [unchecked] unchecked conversion
    found : java.util.List
    required: java.util.Collection<? extends java.lang.Integer>
    arl=new ArrayList<Integer>
    (collectModulos(a).subList(1,collectModulos(a)
    .size()));
    ^
    1 warning

    The warning must be because collectModulos(a).subList(1,collectModulos(a).size()) returns something that is not an ArrayList<Integer> - maybe just a plain ArrayList. If you're sure it's correct anyway, then you can ignore it.
    However, that method contains much more code than it needs to: You're initializing arl where you declare it, but then on the next line you're immediately initializing it again, discarding the first ArrayList you created. Better would be this:
         public ArrayList removeZero(int a){
            ArrayList<Integer> arl;
            arl=new ArrayList<Integer>(collectModulos(a).subList(1,collectModulos(a).size()));
            return arl;
        }Furthermore, you don't really need to create a local variable to return it, you can create and return an object in one go, like this:
         public ArrayList removeZero(int a){
            return new ArrayList<Integer>(collectModulos(a).subList(1,collectModulos(a).size()));
        }

  • Unchecked Exception using 1.5 Concurrent Libraries

    Sorry to post this here, but it IS related to generics. I'm either doing something wrong, or the concurrent libraries are missing some methods in the ThreadPoolExecutor class.
    I'll try and be brief. When I compile my multi-threaded application with lint on, I get the following error:
    "TransactionsByStore.java:309: warning: [unchecked] unchecked conversion
    found : java.util.concurrent.LinkedBlockingQueue
    required: java.util.concurrent.BlockingQueue<java.lang.Runnable>
    threadPool = new ThreadPoolExecutor(threadCount, threadCount, threadTimeout, TimeUnit.SECONDS, threadQueue);"
    The problem is my "threadQueue" class. It is of type LinkedBlockingQueue<java.util.concurrent.Callable> since Callable allows the class to return something from the "call" method. It appears that most classes in the concurrent libraries prefers Callable classes over Runnable, but the constructor for a ThreadPoolExecutor appears to only accept a thread queue that holds Runnables. That doesn't seem correct.
    Does anyone know if there is something that I am doing wrong here, or is this just a current limitation of the ThreadPoolExecutor class?
    Thanks.

    The problem is my "threadQueue" class. It is of type
    LinkedBlockingQueue<java.util.concurrent.Callable>
    since Callable allows the class to return something
    from the "call" method. It appears that most classes
    in the concurrent libraries prefers Callable classes
    over Runnable, but the constructor for a
    ThreadPoolExecutor appears to only accept a thread
    queue that holds Runnables. That doesn't seem
    correct.
    Does anyone know if there is something that I am
    doing wrong here, or is this just a current
    limitation of the ThreadPoolExecutor class?OK, so I just did some reading and I now better understand the context of your question:
    * ThreadPoolExecutor is an ExecutorService, not just an Executor, so it handles Callables in addition to Runnables
    * You're taking the slightly unusual step of constructing your own instance, presumably because you've determined none of the predefined ExecutorServices that the Executors factory class creates are suitable for your task?
    * As you wish to use the ThreadPoolExecutor to execute Callables, you want to know why the constructor takes BlockingQueue<Runnable> rather than BlockingQueue<Callable>
    So firstly, this question really has nothing to do with generics. Callable isn't a Runnable and as such there's no way you're ever going to be able to pass a BlockingQueue<Callable> into this method. Therefore it's a question about the design of the concurrency libraries. As such you'll probably get much better quality answers in a forum dedicated to that subject.
    Having said that:
    From what I see the ExecutorService.submit() methods that support Callables are all implemented in the AbstractExecutorService class that is the superclass for ThreadPoolExecutor.
    So I read the source code for that class. Turns out every Callable passed to submit() is wrapped in a FutureTask, which is a class that imlements Future<V> and Runnable. This makes perfect sense if you think about it - given that this ExecutorService executes things asynchronously, clearly a Future<V> is required if you want to be able to actually get at the result.
    Thus since Callables are wrapped in a class that's Runnable inside the ExecutorService, that's how it is able to handle Callables using a BlockingQueue<Runnable>.
    So... is it important to you that the queue you pass in is a BlockingQueue<Callable> or can you simply make it a BlockingQueue<Runnable>?
    You're never going to be able to constrain the type of the BlockingQueue to be anything stricter than Runnable, BTW. This is because the ThreadPoolExecutor executes Runnables as well as Callables, so if you were allowed to pass in a BlockingQueue<FutureResult> (for example) then it wouldn't work because the execute(Runnable) method wouldn't be able to add the Runnable to the queue without wrapping it in a spurious FutureResult.

  • Unchecked or Unsafe operation -- recompile

    Hi,
    How can I set compiler options in Jdeveloper?
    I am getting a
    Note: C:\JDeveloper10131\j2ee\home\application-deployments\AbcEJBTest\AbcEJB\ejb_webs
    ervice1\runtime\ControllerResponseElement_LiteralSerializer.java uses unchecked or unsafe operations
    Note: Recompile with -Xlint:unchecked for details.
    I am looking to recompile with the "-Xlint:unchecked" option.
    Thanks.

    See Generics : compiler option : unchecked conversion warnings

  • Question about assignment conversion

    JLS Third Edition, chapter 5.2 on page 93 and Discussion (p. 94), states that:
    >
    It is a compile time error if a chain of conversions contains two parametrized types that are not in a subtype relation.
    And in the Discussion the following example is shown:
    Integer -> Comparable<Integer> -> Comparable -> Comparable<String>
    Which rocks, since Integer and String are not in a subtype relation. This is still possible because of support for legacy code (i.e. raw types).
    However I wrote the following dummy code:
    Integer a = 1;
              Comparable<Integer> ci = a;
              Comparable c = ci;
              Comparable<String> cs = c;expecting the compiler to 'trace' the chain of conversions and throw a compile-time error, but all it did was to produce an unchecked conversion warning when the value of the reference variable c is assigned to the reference variable cs.
    Isn't this in contrast with what stated by JLS?

    First, is there any particular reason why you used:
    Integer a = Integer.valueOf(1);while I used
    Integer a = 1; //boxing
    Just to get rid of boxing conversion as a possible issue--which it shouldn't be, but might as well keep it simple.
    Integer a = Integer.valueOf(1);
    Comparable<String> cs1 = a; // errorbecause we are assigning to a Comparable<String> an
    Integer value, and that's illegal, since String and
    Integer are not in a subtype relation (?)Something like that, yes. I'm not sure of the exact clause of the JLS that forbids it.
    >
    Comparable<Integer> ci = a; // ok
    Comparable<String> cs2 = ci; // errorbecause we are assigning to a Comparable<String> a
    Comparable<Integer>, and again, String and Integer
    are not in a subtype relation (?)Yep.
    Comparable<String> cs3 = c1; // warning
    Comparable<String> cs4 = c2; // warningit's what I believe is called 'heap pollution' I forget what that term means, and am too lazy to look it up, so I'll take your word for it.
    and I
    believe that on first use a ClassCastException will
    be thrown Sounds right. Run it and see for yourself.
    (although the compiler behaves correctly by
    flagging an unchecked warning, for compatibility with
    legacy systems, etc)Right.

  • -Xlint: Unchecked Error Explanation

    I have done a compile with -Xlint: Unchecked and i have got back the following results.
    [Unchecked] Unchecked Conversion
    [Unchecked] Unchecked Method invocation: <T>sort[java.util.List<T>,java.util.Comparator<? super T>in java.util.Collections is applied to [java.util.ArrayList<Album>, java.util.Comparator]It relates to
    if ( type==( 1 ) )
                    Collections.sort(list, Album.NameComparator);
                  PrintJButton.doClick();
    public int compareTo(Object anotherAlbum) //A compareTo method is needed when implementing comparable on your class
         if( !(anotherAlbum instanceof Album) )  //comparing
                   throw new ClassCastException("Instance of Album expected");  //exception handling
                   int anotherAlbumArtistName = ((Album)anotherAlbum).getID();  //standard sort on my getID() method
                   return this.noOfTracks - anotherAlbumArtistName;   //returns the inputs in sorted accesending order
    public static Comparator NameComparator = new Comparator() //creating a new name comparator object which is integrated
                                                              //within my comparable Album.
         public int compare(Object album, Object anotherAlbum) //Accepts to Album objects at a time for comparison
                String make1 = ((Album)album).getName().toUpperCase();   //comparing on my Album Names
                String make2 = ((Album)anotherAlbum).getName().toUpperCase();
                return make1.compareTo(make2);   //returning Album name sorted from a-z
    public static Comparator cdComparator = new Comparator() //creating a new cd comparator
         public int compare(Object album, Object anotherAlbum) //accepts to album ojects
                String make1 = ((Album)album).getCD().toUpperCase();  //comparison on my cd names
                String make2 = ((Album)anotherAlbum).getCD().toUpperCase();
                return make1.compareTo(make2);   //returning cd name sorted from a-z
    }Does anyone know what is wrong?

    You've got two different things going on here. You're mixing Comparators and Comparables.
    If Album is to be Comparable, then that means it has a "natural" order, and you'd declare it as public class Album impelements Comparable<Album>[/ode], and you'd provide a compareTo(Album) method so that it can be compared to other albums, and a list of Albums can be sorted without providing an external Comparator class.
    If you just want Comparators--external classes that order pairs of Albums, then don't make Album Comparable, and don't implement compareTo.
    Or, you can do both.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Unchecked problem while compiling

    When compiling, I get a non-fatal warning, 'unchecked', what ever that means. It is the command flag Xlint-unchecked or something.
    The code is a static hashtable which I am statically putting elements into:
    public static Hashtable variables = new Hashtable();
    static{
      variables.put("###",...);
      //another 30 lines or so of the same...
    }1. What does unchecked mean?
    2. Why does the Hashtable give me this warning?
    3. How can it be fixed?
    Thanks

    This all has to do with the addition of generics to Java 5. Generics allow the specification of data types in the code so that errors (for instance, placing a String value in a hashtable intended to hold Integers) can be detected at compile time rather than run time.
    You are compiling some code that doesn't specify the data type.
    Add the following to the javac option to see the details of the warning. (See the javac documentation.)
    -Xlint:unchecked
    Give more detail for unchecked conversion warnings that are mandated by the Java Language Specification.
    Refer to this for what to do to fix it:
    http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html

  • To find number of parameter from request

    Freinds,
    Is there any way to find out number of parameter submitted from request object. But the constraint will be with out going through loop.
    Example
    int count = 0;
              Enumeration list = request.getParameterNames();
              while (list.hasMoreElements())     {
                   count++;
                   list.nextElement();
              }

    Can some body help me to resolve the warning created by this line
    ArrayList paramList = null;
    paramList = new ArrayList(Collections.list(request.getParameterNames()));CheckFilter.java:96: warning: [unchecked] unchecked conversion
    found : java.util.Enumeration
    required: java.util.Enumeration<T>
    paramList = new ArrayList(Collections.list(request.getParameterNames()));
    ^
    CheckFilter.java:96: warning: [unchecked] unchecked method invocation: <T>list(java.util.Enumeration<T>) in java.util.Collections is applied to (java.util.Enumeration)
    paramList = new ArrayList(Collections.list(request.getParameterNames()));
    ^
    CheckFilter.java:96: warning: [unchecked] unchecked call to ArrayList(java.util.Collection<? extends E>) as a member of the raw type java.util.ArrayList
    paramList = new ArrayList(Collections.list(request.getParameterNames()));

Maybe you are looking for

  • FPGA memory limitation

    Hi... I have tried to use more than 2 MB memory (using memory blocks) on FPGA. During compilation Xilinx tool chain generated error "AR #21955"....which is explained as memory limitation (in xilinx website). Can't we create memory blocks of more than

  • Good Virus protection Apps to use for the DroidX?

    Just wondering if anyone recommends good Virus protection for their phone.  Thx!

  • Finder cannot search word document contents osx 10.8.3

    Dear all-- I just got a new computer with osx 10.8.3.  I would like to search current folder for a particular word in a microsoft word document.  The finder window has an option for 'contents', but can only see this word in .pdf files, not any other

  • Selecting color in color picker?

    After selecting a hue in the spectrum, are all of the different shades or variations of that color in the color field the exact same color, only with different saturation and brightness values? Thanks.

  • Mac shuts down on sleep command

    I have a 5 or 6 year old G4 Quicksilver 733. It has developed the habit of shutting down when I tell it to sleep. I have renewed PRAM battery and tried re-setting PMU, but still shutting down. Any suggestions?? Many thanks. Geoff