Warning: [unchecked] unchecked cast.

Hello!
I have a problem with this code.
I get:
warning: [unchecked] unchecked cast.
How should i do the cast?
Or is it something else that i have done wrong?
Socket socket = new Socket("localhost", this.port); 
LinkedList<String> times = new LinkedList<String>();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
try
    times = (LinkedList<String>)ois.readObject();
catch(ClassNotFoundException cnfe)
}

That's because it is not 100% sure (at compile time) that the object is really of a type LinkedList<String>, that's why you received a warning (note that this is just a warning: not an exception or error). You cannot do anything about is. You could suppress the warning like this:
    @SuppressWarnings("unchecked")
    void yourMethod() {
        try {
            Socket socket = new Socket("localhost", 666); 
            LinkedList<String> times = new LinkedList<String>();
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            times = (LinkedList<String>)ois.readObject();
        } catch(Exception cnfe) {
            cnfe.printStackTrace();
    }Good luck.

Similar Messages

  • Warning: [unchecked] unchecked cast found

    I am getting the following warning when I compile my code. Please help.
    warning: [unchecked] unchecked cast
    found : java.lang.Object
    required: java.util.Vector<java.lang.Long>
    copy.path = (Vector<Long>) this.path.clone();
    1 warning
    Here is the code
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package cs572project1;
    import java.util.*;
    * Richard Becraft
    * 1/22/2010
    * CS 572 Heuristic Problem Solving
    * This class represents a node in a search tree of a graph that represents a street map.
    public class SearchNode implements Cloneable {
    public long depth;
    public double costSoFar;
    public double estimatedCostToGoal;
    public Vector<Long> path;
    public SearchNode() {
    depth = -1;
    costSoFar = -1;
    estimatedCostToGoal = -1;
    path = new Vector<Long>(20, 20);
    public void printSearchNode() {
    System.out.println("\n****In printSearchNode");
    System.out.println("depth: " + depth + " costSoFar: " + costSoFar + " estimatedCostToGoal: " + estimatedCostToGoal);
    for (Enumeration<Long> e = this.path.elements(); e.hasMoreElements();) {
    System.out.println(e.nextElement());
    System.out.println("****Exiting printSearchNode\n");
    @Override
    public SearchNode clone() {
    SearchNode copy;
    try {
    //System.out.println("in clone SearchNode");
    copy = (SearchNode) super.clone();
    copy.path = (Vector<Long>) this.path.clone(); // <<<< the offending line
    //copy.path = new Vector<Long>(this.path.capacity());
    //this.printSearchNode();
    //System.out.println("copy.path.size: " + copy.path.size());
    //System.out.println("this.path.size: " + this.path.size());
    //System.out.println("copy.path.capacity: " + copy.path.capacity());
    //System.out.println("this.path.capacity: " + this.path.capacity());
    //Collections.copy(copy.path, this.path);
    } catch (CloneNotSupportedException e) {
    throw new RuntimeException("This class does not implement Cloneable " + e);
    return copy;
    }

    rickbecraft wrote:
    I am getting the following warning when I compile my code. Please help.
    warning: [unchecked] unchecked cast
    found : java.lang.Object
    required: java.util.Vector<java.lang.Long>
    copy.path = (Vector<Long>) this.path.clone();The variable path has a type of Vector but clone() returns an Object. It is only a warning, not an error, so you can ignore it - I think you can be confident that clone() will always return a Vector. A slightly more typesafe approach (in my opinion) is to create a new Vector<Long> using the constructor that takes a Collection as an argument, passing in the Vector that you want to clone. Something like
    copy.path = new Vector<Long>(this.path);

  • 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

  • Warning: [unchecked] unchecked call to getMethod when updating to JDK 1.6

    I'm received the following compilation warnings after I switched to Java 6 from Java 5:
    warning: [unchecked] unchecked call to getMethod(java.lang.String, java.lang.Class<?>...> as a member of the raw type java.lang.Class
    removeChangeListener = myParent.getMethod("removeChangeListener",
    changeListenerParameterTypes);
    The code is this class is instantiated by many classes. The class instantiating this class is passed through a constructor.
    Here is a partial code snippet of the class, constructor and method where the warning occurs:
    public class DumpDisplay extends javax.swing.JFrame implements javax.swing.event.ChangeListener
    private Class changeListenerParameterTypes[] = new Class[2];
    public DumpDisplay(Object mvc)
    Class myParent = mvc.getClass();
    public void removeListeners()
    Method removeChangeListener = null;
    changeListenerParameterTypes[0] = ChangeListener.class;
    changeListenerParameterTypes[1] = Integer.TYPE;
    // Get the removeChangeListener method from the MVC class
    try
    removeChangeListener = myParent.getMethod("removeChangeListener",
    changeListenerParameterTypes);
    catch (NoSuchMethodException e)
    System.out.println(" DumpDisplay class addChangeListener method: "+e);
    This compilation warning does not appear in JDK 1.5. Any assistance is greatly appreciated.

    Class myParent = mvc.getClass();Class<?> myParent = mvc.getClass();

  • Warning about unchecked call

    What does it mean?
    warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.Vector properties.add(prop);
    and how can I avoid this warning? what shall i check?

    If you use -Xlint, it will tell you the line number.
    Basically, though, you are compiling in j2se 1.5.0, but not specifying the type for the Vector. That is, you are using it in it's pre 1.5.0, raw mode, and it cannot do any compile time type checking for you.
    Say you were using your vector to store Integers. You would declare it as Vector<Integer> myIntegerVector = new Vector<Integer>();and the warning would go away. Now the compiler can do compile time type checking, and let you know when you are using that vector with a type other than Integer, which might not be safe.
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Jdeveloper warning uses unchecked or unsafe operations

    Greetings:
    I am getting warnings on my oc4j console that look like :
    Note: C:\product\10.1.3\OracleAS_1\j2ee\home\application-deployments\pl\plBeans\generated\PlLoginPrefixesEJB_StatelessSessionBeanWrapper9.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    I get these when I use a JDeveloper created SessionEJB bean. Is there something i can do to "fix" this or should i just ignore it?
    Thanks
    troy

    Hi,
    I have the following code which I have got from a book but when I compile I get a warning .... uses unchecked or unsafe operations.
    class CompTypeComparator implements Comparator
      public int compare(Object o1, Object o2)
        int j1 = ((CompType)o1).j;
        int j2 = ((CompType)o2).j;
        return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));
    public class ComparatorTest
      public static void main(String[] args)
        CompType[] a = new CompType[10];
        Arrays2.fill(a, CompType.generator());
        System.out.println("before sorting, a = " + Arrays.asList(a));
        Arrays.sort(a, new CompTypeComparator());
        System.out.println("after sorting, a = " + Arrays.asList(a));
    }I have met this error before in other code from the book and have been able to sort it by myself. This one I could not solve since I do not fully understand the syntax of the Arrays.sort() method. IE
    sort(T[] a, Comparator<? super T> c)Presumably this error is because the book used an older version of the compiler than the version I am using (V5.0 or is it V1.5).
    Could anyone explain the error, how I can solve it and what the sort method means particularly "? super T"?
    Regards FarmerJo

  • Warning:unchecked cast

    I am one of the many that have this compiler problem. When i compile this program( i want to check how it works).
    import generated.*;
    import javax.xml.bind.*;
    import java.io.File;
    import java.util.List;
    public class JAXBUnMarshaller {
      public void unMarshall(File xmlDocument) {
        try {
    JAXBContext jaxbContext = JAXBContext.newInstance("generated");
    Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
    JAXBElement<CatalogType> catalogElement =     (JAXBElement<CatalogType>)
    unMarshaller.unmarshal(xmlDocument);
    CatalogType catalog=catalogElement.getValue();
         System.out.println("Section: " + catalog.getSection());
         System.out.println("Publisher: " + catalog.getPublisher());
         List<JournalType> journalList = catalog.getJournal();
         for (int i = 0; i < journalList.size(); i++) {
              JournalType journal = (JournalType) journalList.get(i);
              List<ArticleType> articleList = journal.getArticle();
                for (int j = 0; j < articleList.size(); j++) {
                  ArticleType article = (ArticleType)articleList.get(j);
    System.out.println("Article Date: " + article.getDate());
    System.out.println("Level: " + article.getLevel());
    System.out.println("Title: " + article.getTitle());
    System.out.println("Author: " + article.getAuthor());
    catch (JAXBException e) {
    System.out.println(e.toString());
         public static void main(String[] argv) {
              File xmlDocument = new File("catalog.xml");
              JAXBUnMarshaller jaxbUnmarshaller = new JAXBUnMarshaller();
              jaxbUnmarshaller.unMarshall(xmlDocument);
    IT responds to me
    _JAXBUnMarshaller.java:15:warning: [unchecked] unchecked cast_
    found: java.lang.Object
    required:javax.xml.bind.JAXBElement(generated.CatalogType)
    Can anyone help?

    Yep. Looks as if that's 'cause of
    JAXBElement<CatalogType> catalogElement = (JAXBElement<CatalogType>)unMarshaller.unmarshal(xmlDocument);The Java compiler is warning you that it has no way of ensuring (either at compile time or at runtime) that the JAXBElement is actually an element with the type CatalogType. So if you're wrong, things won't work the way you expect.
    You can safely ignore this warning if you're certain you're correct; the compiler is just drawing your attention to the possibility. Ideally, you'd have an API that returned the correct type rather than just an Object, but the Unmarshaller class doesn't have that capacity. So you'll just have to check it yourself to make sure it's right.

  • Cloning a Vector String causes warning: unchecked

    I have a Vector<String> that I want to clone and store in another Vector<String>. I can't figure out why I get a warning.
    Vector<String> DATA = new TestData1().getData();
    Vector<String> nuDATA;
    //@SuppressWarning( "unchecked" )
    nuDATA = (Vector<String>) DATA.clone();The warning i get is "warning: [unchecked] unchecked cast"
    found: Object
    required: Vector<String>
    So I understand the clone() function returns an Object. But why on earth can't I cast it into a Vector<String>?
    Also, the SuppressWarning line of code causes its own error when uncommented...
    Message was edited by:
    pfhat

    True, and due to the fact that it always will be a Vector<String> and never anything else, there really is no need to "fix" this.
    BUT
    that being said, it's not 'graceful' the way it is now, and that annoys me. Plus maybe in the future i'll need to know how to do this the right way.

  • Unchecked Cast

    i have a code fragment
    Map<Integer,Settore> settori = (Map<Integer,Settore>) sessione.getAttribute("settori");
                if (settori == null) {
                    sessione.invalidate();
                    request.setAttribute("messaggioErrore", messaggioErrore1);
                    getServletContext().getRequestDispatcher("/errore.jsp").forward(request, response);
                    return;
                }that produce this warning (compiling with -Xlint)
    C:\Users\Nino\Documents\Workspace_NetBeans\GEM10\src\java\control\Aggiungi.java:85: warning: [unchecked] unchecked cast
    found   : java.lang.Object
    required: java.util.Map<java.lang.Integer,model.Settore>
                Map<Integer,Settore> settori = (Map<Integer,Settore>) sessione.getAttribute("settori");i can't understand why...why an unchecked cast!
    "settori" attribute is a Map<Integer,Settori>!
    Someone can help me please?

    this is a compile time warning; java can only know during runtime what type of object will actually be in the session; because the session is defined as an <Object,Object> map you can put basically anything in there, which is the flexibility you would expect from the session.
    To the compiler however you are now casting an Object to a <Integer, Settore> map, which COULD go wrong during runtime. Hence the unchecked warning, it is only there to make sure you know what you are doing, meaning you have to add the unchecked annotation.

  • Describe non-generic array cast in JLS3 as being unchecked

    This method :
        static <T, U extends T> U[] cast(T[] a) { return (U[]) a; }will generate the warning: [unchecked] unchecked cast, found: T[], required: U[].
    And it should. Wouldn't it be appropriate if
        static Object[] cast(String[] a) { return (String[]) a; }would produce the same warning?
    If you do that, you could translate the declaration
      T[] at = new T[255]
      String[] as = new String[255]into
    Array<T> at = Array.<T>newInstance(255);
    Array<String> as = Array.<String>newInstance(String.class, 255);where java.lang.reflect.Array would be something like
    package java.lang.reflect.Array;
    public final class Array<T> implements Iterable<T> {
        public final int length;
        private Type memberType;
        private Array(Type memberType, int length) {
            this.memberType = memberType;
            this.length = length;
        public native T getMember(int i);
        public native void setMember(int i, T member);
        public native java.util.Iterator<T> iterator();
       public static <U> Array<U> newInstance(int length) {
           return new Array<U>(null, length);
       public static <U> Array<U> newInstance(Class<U> memberClass, int length) {
           return new Array<U>(memberClass, length);

    Sorry, I created a bad example. It should have been:
        static <T, U extends T> T[] cast(U[] a) { return (T[]) a; }and
        static Object[] cast(String[] a) { return (Object[]) a; }The point is that an array of String is different from an array of Object and casts between them is unsafe. Throwing an ArrayStoreException if the wrong type is assigned is just a workaround for lack generic types in pre-Tiger Java. Now that we will have generics, I think it would be appropriate if Java arrays would be treated as proper generic types. For those that are afraid of breaking backwards compatiblility, the erasure mechanism should be able to take care of that.

  • Netbeans warning: unchecked/unsafe operations

    I get the following warnings when I compile my project in netbeans:
    Note: Some input files use unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    When I re-compiled, I get 37 warnings similar to:
    warning: [unchecked] unchecked call to addElement(E) as a member of the raw type java.util.Vector
    all involving adding/inserting/removing elements in a vector...any ideas why?

    if you're not using 1.5, you can turn off the warnings by changing the source compability level in NetBeans. In your Project Properties, look under the Sources node at the bottom of the window you'll see a "Source Level" drop-down list. Change it to 1.4.

  • JDK 6: Generics: List.add() question - keep getting unchecked call warning.

    JDK 6
    Generics
    private TreeNode transactionTreeData;
    transactionTreeData.getChildren().add(moduleData);1. transactionTreeData is a TreeNode.
    2. the method getChildren() returns a java.util.List
    3. the method add() is from the Collection interface.
    I keep returning the warning message:
    "unchecked call to add(E) as a member of the raw type java.util.List"
    I understand what this means, but I am having problems rewriting these lines correctly to remove the warning.
    I've tried:
    private TreeNode transactionTreeData;
    List<TreeNode> treeList = transactionTreeData.getChildren();
    treeList.add(moduleData);But I keep returning the same warning message. I guess what is throwing me off is how to I properly add the generic statements when the List is return from a method (getChilden in this example)?
    Thanks,
    --Todd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    This is actually JSF - MyFaces Tomahawk to be exact, my mistake for not adding that in my original thread.
    I am dealing with the compiled class:
    package org.apache.myfaces.custom.tree2;
    public interface TreeNode extends java.io.Serializable {  
         java.util.List getChildren();
    }TreeNode.getChildren return a raw List as you can see, no doubt...
    Thanks,
    --Todd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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 .

  • Unnecessary cast warning...I can't figure out why

    I've got my compiler warning me of unnecessary casts, and this method generates one of the warnings:
        public static<T> T doIt(T input) {
            Object result = null;
            return (T) result; // Warning: Unnecessary cast to type T for expression of type Object
        }Can anybody explain why it doesn't like me casting to type T? I get a compiler error if I don't make the cast.
    Thanks.

    I think that the article is a bit of a red herring in this particular case. Whilst it's true that erasure means that the generic type information is lost at runtime, generic type information most certainly is not lost at compile time - that's the whole point of generics - to be typesafe at compile time.
    In this case, we clearly have an Object reference, which could refer to any object (though in this case it refers to null), and it's being assigned to a T reference, hence the need for an explicit downcast. Remove it and you get the following error
        Warning:  line (5) [unchecked] unchecked cast
                           found   : java.lang.Object
                           required: Twhich is as expected, and illustates the point that the case is clearly not 'unnecessary'.
    Regarding Eclipse, if you can't find out the command line arguments to javac try creating an Ant build script to do the compilation for you. The execution log of the script will tell you exactly what was passed to javac, and it's resulting output. Furthermore, since support for Java 5.0 in the development branch of Eclipse is currenty under active development, many problems such as this are bound to crop up. When you do run up against another problems again, you can use the Ant build script to determine whether or not the problem lies with Eclipse or the JDK. If it's Eclipse, you've a better chance of having the problem resolved throught the Eclipse forums and/or bug tracker.

  • 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()));
        }

Maybe you are looking for

  • Can I print to my airprint printer if I am not on the same wireless network?

    I am trying to print to my printer (HP Color LaserJet Pro MFP M476nw) when I am on the road working. This printer is in my home office and I want to be able tp send items to it during the day so that they are printed and ready when I return at the en

  • Using XI with native netweaver JMS provider

    I have configured an XI interface to use the provided netweaver JMS service provider. The interface takes and IDoc and posts it to the JMS queue, however, when the target application goes to retrieve the message off of the queue, it is in the format

  • How can i view data files and print them?

    I'm collecting very large data files with the DAQ. Afterwards I'd like to be able to view them (zooming in and out and scrolling) then print when I get a view I like. How can I do this? Is there code out there already? What are some ways of easily vi

  • Upgrade 10.2.0. 3 to upgrade 10.2.0.4

    While applying the patch set for 10.2.0.4 there is screen for Oracle Configuration Manager Registration,If I do not enable that at upgrade time ,how can I regiser later? Thanks

  • How to create a Lion Boot Disc?

    Hi there, When Lion was release I updated from the App Store. I recently had to Repair my HDD using Disc Utilities and DU wanted me to boot from an install disc . . . guess what . . . no install disc. (Well I do have my Leopard install disc) How does