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.

Similar Messages

  • How to avoid "unchecked cast" warnings

    Hi all,
    here is my code:
    private Vector<String> vector1;
    private Vector<String> vector2=new Vector<String>();
    vector1=(Vector<String>)vector2.clone();
    ...How can i avoid "unchecked cast" warnings, while compiling with "-Xlint:unchecked" option.

    I'd also add that you should think about the following idioms:
    1. Ask yourself do I really need a synchronized structure? The answer might be that unsynchronized structure like ArrayList might be more appropriate. If you DO need a concurrent structure then you may find high-performance one in java.util.concurrent package.
    2. Using interfaces will be more appropriate in the long run:
    List<String> l = new ArrayList<String>(); because you can replace the implementation of the specific interface with more appropriate structure just on one place.
    Best regards,
    Andrej

  • Is it possible to avoid unchecked cast warning here?

      interface MyRemote extends java.rmi.Remote {}
      public <T extends java.rmi.Remote> Class<T>[] getRemoteInterfaces() {
        return (Class<T>[]) new Class[] { MyRemote.class };  //  <-- unchecked cast
      }

    public Collection<Class<? extends Remote>>
    getRemoteInterfaces() {
    Collection<Class<? extends Remote>> c = new
    ArrayList<Class<? extends Remote>>(1);
    c.add(MyRemote.class);
    return c;
    }Just for comparison, without judgement over applicability:
    public Collection getRemoteInterfaces() {
        List list = new ArrayList(1);
        list.add(MyRemote.class);
        return list;
    }/k1

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

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

  • Possible solution for unchecked casts?

    Proposal: add to java.lang.reflect.Type the following methods:
    /** Determines if the specified Object is assignment-compatible with the object
    * represented by this Class. This method is the dynamic equivalent of the
    * Java language instanceof operator. The method returns true if the specified Object
    * argument is non-null and can be cast to the reference type represented by this Class
    * object without raising a ClassCastException. It returns false otherwise.
    public boolean isInstance(Object obj)
    * Casts an object to the class or interface represented by this Class object.
    * Checks all fields in the object that they are of the proper type by calling
    * types.class.instanceof() recursively.
    public T Class.cast(Object obj, java.lang.reflect.Type ... types)
    Then any unchecked cast
    Object obj;
    T0<T1, .. Tn> checked = (T0) obj;could implicitly be converted to:
    Object obj;
    T0<T1, .. Tn> checked = T0.class.cast<obj, T1.class, ... Tn.class);No more unchecked casts in the compiled classes!

    Well, neither the code above nor the code referenced
    in the link to the other discussion above compiles with the
    1.5.0 beta compiler :)
    But the referenced example does! To be sure, here's the faulty but compilable example again:
    public class HiddenCheckedExceptions
      public static void main(String argv[])
        throwHidden(new Throwable());
      public static void throwHidden(Throwable t)
        ExceptionHider a = new ExceptionHider(t);
        ExceptionHider<RuntimeException> b = a;
        b.throwHidden();  // this is line 8
      private static final class ExceptionHider<T extends Throwable>
        private final T t;
        ExceptionHider(T t)
          this.t = t;
        void throwHidden() throws T
          throw t;
    }When running it throws:
    Exception in thread "main" java.lang.Throwable
            at HiddenCheckedExceptions.main(HiddenCheckedExceptions.java:8)Either a ClassCastException should be thrown during the assignment of a to b, or it should not compile at all.

  • How to get rid of this unchecked cast warning?

    Vector<Integer> v1 = new Vector<Integer>(); // ok
    Object obj = (Object) v1; // ok
    Vector<Integer> v2 = (Vector<Integer>) obj; //unchecked cast
    It works when I try to cast Vector<Integer> to Object. However, it prompts "unchecked cast warning" when I try to cast the object back to Vector<Integer>. How can I get rid of this warning? Is there something wrong?

    There is nothing wrong (it is just a warning).
    In the new type system, you would later do something like
    Integer n = v2.get(14);Now the compiler cannot check (compile time maybe, run time never) whether obj is of class Vector<Integer> (Only Vector), as at compile time as type parameters are stripped away in java1.5 at run time ("type erasure").
    So later the assignment to n could throw a class cast exception at run time.

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

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

  • Casting, generics and unchecked expressions

    Hi
    I'm trying to access a vector of Recommendations held by a Person object, but I don't want to allow direct access to the vector, just the information contained in it
    public Vector<Recommendation> getRecommendations() {
         return((Vector<Recommendation>)recList.clone());
    }The trouble I'm having is that I have to cast the recList.clone() as a Vector<Recommendation> to return a compatible type.
    When I do this, the source compiles with a warning: unchecked cast.
    Could someone explain an unchecked cast and give me a pointer to solving this please? I've not managed to find anything about combining generics and clones in my books. Is there another way of returning a copy of the vector? All I want to do is make the objects in the vector available for viewing, via processing in a servlet, to a jsp.
    Thanks in advance

    YoGee wrote:
    What you are exposing is a Vector with a reference to a clone of the internal data array, you are not cloning the elements in that data array. So basically if you modify an element in one Vector chances are it will be reflected in the other (assuming the element is mutable).Thanks for the reply.
    I should have said that what I want to achieve is:
    make the Vector<Recommendation>recList contents available for viewing, but not expose the objects so that they are able to be changed - so what I have done is not good!
    after some thought, what I really want is this:
    If what you actually want to achieve is a deep clone (i.e. clone the elements in the internal data array) you need to do it yourself by looping through the Vector and cloning each element in it (assuming the elements implement clone properly)so thanks for the help!

  • Question on Cast & generics

    Only an unfinished idea (formulated as question in a may be wrong forum):
    One of the big strength of generics is, that explicit cast may be avoided in many cases.
    From day one Java inserted cast by itself where possible and clear. Using + in print() for all
    kind of objects is a cast to (String) and this is handled via a special methods toString()
    in Object.
    I was always wondering, why a cast to type T is not treated as a "normal" operation , in case
    where the cast is not well specified in the language or via generics. Now it inevitably leads to
    an exception, without even sending a cast-message to the object.
    Would it not be much more OO/Generic, to call something like <T> T cast(Class t) method
    located in Object with a default behavior (throwing an cast-exception), which can be overriden
    in classes to react individually on those casts, and not only in the special case +(String)object
    by calling object.toString() .

    thread "Request for non-throwing cast!" and your reply no. 7 and 9The 'design flaw' reply (no 8) by dcminter holds, but sometimes you have to work with imperfectly designed APIs, and that just have to use multiple if/then/else if ... constructs. This in turn doesn't mean that you have encourage bad design by providing default behaviour. See also reply 21 by lucretius.
    and the track "Possible solution for unchecked casts?"That thread is not about providing new default behaviour, it is about restricting/improving present default behaviour (the unchecked cast)
    But you may answer cast is not an operator.Cast is an operator, but it returns it's argument untouched when it doesn't throw a ClassCastException. This rule allows the compiler to optimize and remove type checks if it can prove that the cast's argument will be of the desired type. In combination with parameterized types, that has proven to be difficult ;)
    I assume you want the Object.as() method because you find yourself writing the same conversion code on different places. In that case, I would advise to create some kind of Converter object that contains the convert() method:
    interface Converter<T,U> {
       /** Convert an object from class T to class U. */
       U convert(T t);
       Class<T> getFromClass();
       Class<U> getToClass();
    abstract class ConversionManager {
       /** get a converter that converts an object to class U. */
       public abstract <T,U> Converter<T, U> getConverter(Class<T> from, Class<U> to);
       /** register a converter that converts an object from class T to U. */
       public abstract <T,U> void registerConverter(Converter<T,U> cnv);
       /** Convert an object to class U. */
       public <T,U> U as(Class<T> tClass, Class<U> uClass, T t) {
          return getConverter(tClass, uClass).convert(t);
    }Because this allows for multiple conversion managers, you can use different conversions on different places.

  • Generic unchecked problem

    Hi All,
    I have a problem with the following code . Can any one help me to over come the warning.
    Here is my code:
    import java.util.*;
    public class CastEx {
    public CastEx() {
         Vector<String> v1 = new Vector<String>(); // ok
         Object obj = (Object) v1; // ok
         Vector<String> v2 = (Vector<String>) obj ; //unchecked cast
    public static void main(String[] args) {
         new CastEx();
    Warning :
    CastEx.java uses unchecked or unsafe operations.
    Thanks in advance........

    You have some choices:
    1- Learn to live with the warning.
    2- Use the annotation @SuppressWarning("unchecked") before the method or class.
    3- Don't do this type of unchecked cast in your code.
    4- Use another cast:Vector v2 = (Vector) obj;Regards

  • HashMap cast

    HashMap<Object, Object> parameters = (HashMap<Object, Object>) request.getParameterMap();
    this.setRequestContextMap(new HashMap(parameters));
    This is giving me
    warning: [unchecked] cast.
    warning: [unchecked] unchecked call to HashMap(java.util.Map<? extends K,? extends V>) as a member of the raw type java.util.HashMap
    How do I get rid of this warning?
    - J

    specify type arguments for HashMap allocation:
    e.g. new HashMap<Object,Object>(parameters)

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

  • Casting dataVector

    Hello,
    how can the following code be made generics compatible?
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableExample extends JFrame {
      TableExample() {
        DefaultTableModel dm = new DefaultTableModel() {
          public void setValueAt(Object value, int row, int col) {
    /*     Pre-generic accepted code:
         Vector rowVector = (Vector)dataVector.elementAt(row);
    The next line gives:
    TableExample.java:16: warning: [unchecked] unchecked cast
    found   : java.lang.Object
    required: java.util.Vector<java.lang.Object>
            Vector<Object> rowVector = (Vector<Object>)dataVector.elementAt(row);
                                                                           ^
    The circumflex is actually point at "(row)".
    */     Vector<Object> rowVector = (Vector<Object>)dataVector.elementAt(row);
         if (col == 1) {
           double d= 2.;
           rowVector.setElementAt(d, col);
            } else {
           rowVector.setElementAt(value, col);
    }

    Hello,
    thanks for your reply. Changing Vector<Object> back to Vector will bring the compiler warning again (which I am trying to eliminate). dataVector is a field in the DefaultTableModel class, and I don't know how its declaration can be changed - I rather assume it's impossible, unless I create my own model class.

Maybe you are looking for

  • Grouping vendor payments using Grouping key issue

    Hello Gurus, I created a new grouping key in config to be assigned to the vendor master (under Payments Transactions Accounting). The grouping key fields used were BUDAT (Posting Date) and ZFBDT (Baseline Payment Date). The automatic payment program

  • Need help with Apple TV connected to a Bose system

    I have a new Apple TV that I have installed with a Bose Lifestyle 28 home theater system connected by an optical cable.   The TV is also connected to a Directv box with the Directv box being connected to the Bose system via an Optical cable.  I get D

  • Folio builder login error: invalid_request

    Hi InDesig CC. When I start Foli Buildre send the message: An error occurred when trying to log in Folio Builder panel. [invalid_request]. Thank you

  • Wht r types of structures in ABAP

    Hi,      Wht r types of structures in ABAP. Answer rewarded. Regds. Balakri...

  • Why is there no "cancel" button anywhere in OS X?

    In Windows, there is almost always a "cancel" button to undo your changes. So, for example, if you changed a bunch of settings in windows but change your mind, you can hit "cancel" and it'll simply undo everything you changed and exit you out of the