Casting generics

Hello,
without generics the code looks like this
// Get the Map for this particular component
    Object componentMap = components.get(componentName);
    if (componentMap == null)
    { componentMap = new TreeMap();
      components.put(componentName, componentMap);
    return (Map)componentMap;
  }If an Object is null, it is redefined to be a TreeMap. In both cases there is a cast to (Map) on return.
Now I tried
    Map<Object,Object> componentMap = components.get(componentName);
    if (componentMap == null)
    { componentMap = new TreeMap<Object,Object>();
      components.put(componentName, componentMap);
    return (Map<Object,Object>)componentMap;
  }to no avail. Is such a kind of casting at all permitted?
If you would like to have the runnable code, please let me know.
Greetings
J�rg

Yes, how stupid of mine!
Nevertheless I cannot figure out how to make this method "generics compatible".
  private Map getComponentMap(Map components, String key) {
// Get the Map for this particular component
    Object componentMap = components.get(componentName);
    if (componentMap == null)
    { componentMap = new TreeMap();
      components.put(componentName, componentMap);
    return (Map)componentMap;
  }I declared each Map to be of type <Object,Object>.
  private Map<Object,Object> getComponentMap(Map<Object,Object> components, String key) {
    Map<Object,Object> componentMap = (Map<Object,Object>)components.get
(componentName);
    if (componentMap == null)
    { componentMap = new TreeMap<Object,Object>();
      components.put(componentName, componentMap);
    return componentMap;
  }But the compiler says:
"warning: [unchecked] unchecked cast
found : java.lang.Object
required: java.util.Map<java.lang.Object,java.lang.Object>
Map<Object,Object> componentMap = (Map<Object,Object>)components.get(componentName);"
Meaning when an Object is returned by a Map.get(...), then the compiler doesn't want it to be casted, isnt it?

Similar Messages

  • Rules for casting generics type

    I know that there is a section in jsr14 spec about rules of casting generic types, but it seems outdated with
    JLS3.
    It is obvious that e.g. Class<String> cannot be casted to Class<Integer>.
    However in
    <T,V> void foo (Class<T> ct) {
    Class<V> cv = (Class<V>)ct;
    The cast is permitted by the compiler though of course marked as unchecked (The cast should be rejected according to jsr14 spec since none of the types is a subtype of the other).
    So the question is: what are the rules, compiler uses to check casts?

    1. There is an (unsafe) explicit cast from l1 to l2.
    2. There is an implicit cast in the last line, because
    l2 is a List<String>, the line is compiled to the
    equivalent of
    System.out.println(" result:" + (String) l2.get(0));
    // ClassCastException: java.lang.String

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

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

  • Cast generic VI to strictly typed VI

    Is there a way of casting a generic VI to a strictly typed VI through something other than from the Open VI icon?  I'm trying to make a generic VI to handle the open and cast it where I need it.
    Thanks,
    Adrian
    PS.  I should mention that I am using LV 7.0 and have tried to use the "To More Specific Class" icon without success.
    Message Edited by Been bitten by LabVIEW on 10-10-2007 03:18 PM

    Yes, but it won't do you much good. You can't use a type cast (that's not
    allowed), but you can use flatten to string and unflatten to string. That
    way, you basically have what you've asked for.
    All normal properties will work (only tried Panel Open). But the only reason
    to do this, is so you can call the Call By Reference Node. And that will
    fail. The node says something about the vi not being reserved. If you put
    this code inside a sub vi, LabVIEW (8.2.1) will crash (R6025 - pure virtual
    function call). This is not something that you'd want to use.
    There are probably other ways to solve your problem, but you have to explain
    what your higher goal is.
    Regards,
    Wiebe.

  • Request for non-throwing cast!

    Hi there,
    here's something that I'd love to see in Java 1.5:
    A non-throwing cast operator that returns null if the operand is either null or is not of the requested type.
    (For C++ afficionados: Like "dynamic_cast" applied to pointers.
    For C# followers: Like operator "as").
    Since adding a new operator to Java is vastly unrealistic, what about adding a member function
    to java.lang.Class?
    I'm proposing the addition of the following member function to java.lang.Class<T>:
    public T as(Object source)
    return this.isInstance(source) ? (T)source : null;

    How about this, anyway ?
    package com.paperstack.generics;
    * Static methods for use with generics in casting
    * @author Dave Minter
    public class Casts {
       * Generic safe cast
       * @param c The class type to which o should be cast, represented as a Class object
       * @param o The object to be cast
       * @return The object cast to the appropriate type, or null if this would otherwise produce a ClassCastException
      public static <C> C as(Class<C> c,Object o) {
         if( c.isInstance(o) ) return (C)o;
         return null;
    }Invoked thus:
    import static com.paperstack.generics.Casts.*;
    import static java.lang.System.*;
    public class Boom {
      public static void main(String... argv) {
         out.println(as(Integer.class,"Hello"));
         out.println(as(Integer.class,"42"));
         out.println(as(Integer.class,new Integer(43)));
         out.println(as(Integer.class,44));
         out.println(as(Integer.class,null));
    }It's not quite as elegant as yours, but with the static import it's fairly tidy.
    Incidentally, should one be able to do a static import of a class in the default package ? The only reason the above is in a proper package is that I tried creating my illustration in the default package, but the Boom class choked when I tried to do "static import Casts.*". Or is that a bug ?
    D.

  • Modify an object with scripting

    I know I can change the position, but can I change the width of a ListBox with scripting?

    1LMR wrote:
    Rolf,
    OK, there is a Size:Width in the standard Property Node, but I specified "Scripting".  With the green GObj Property Node there is no Size.  It has only Bounds Read Only.
    Regards,
    1LMR
    Scripting is simply an extension to the standard VI Server interface, with no clear boundery other than what NI thinks is not everyday use in properties and methods. The option to disable scripting is mainly to make the object hierarchy and property and method menus less crowded and intimidating to a starting LabVIEW user.
    As such there are properties that apply to any object, and others that apply to a certain group of objects and some that apply only to a specific type. There is no way to set the size of an object on the top level object hierarchy since some objects do not support changing their size at all. So the objects that allow to change their size have such properties in a more class specific level. This means you have to cast generic object refnum into a more specific refnum in order to be able to get at those properties.And you can only cast a refnum into a more specific refnum if the object type actually matches.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Will generics implementation eliminate runtime casting?

    Before generics, one must explicitly cast when pulling out of an iterator. For example:
    List l = ...
    for(Iterator i = l.iterator(); i.hasNext();) {
    doSomethingWithInteger((Integer)l.next());
    Now with generics, we won't have to explicitly cast the return value of the iterator's .next() method:
    List<Integer> l = ...
    for(Iterator i = l.iterator(); i.hasNext();) {
    doSomethingWithInteger(l.next());
    However, form what I've seen of decompiled code compiled with the beta version of the generics compiler, there is still implicit casting going on. The return value of Iterator.next() is still being casted to an Integer. And runtime casting like this has actual instructions to be executed, not just syntactic sugar. It seems silly to me, though, since everything in the List is an Integer, there should be no need to explicitly cast it.
    So will the addition of generics not be able to eliminate this overhead? Why was this decided?

    It actually turns out that the runtime casts are extremely cheap to do, because modern superscalars typically have plenty of extra functional units and branch prediction on the cast is extremely accurate (all the casts inserted by JSR-14 are always true, so the branches always predict correctly).
    But even though they have a negligible performance cost, they do bloat the binary. The NextGen proposal
    http://doi.acm.org/10.1145/286936.286958
    was always the "future" solution to this. It's the second step of the implementation. The first step is JSR-14.

  • All my prints using: Lightroom 5, printer color management turned off, and non-generic ICC profile (e.g. Epson Premium Glossy) have magenta tint or cast

    I'm using PC with: Windows 8.1, 64bit, Lightroom 5.4, Epson R3000, 6.75 (latest) driver, color management turned off in printer settings, Lightroom configured to manage color.  If I use a generic ICC profile such as Epson sRGB, the prints look OK.  But when I use any ICC profile dedicated to my paper and printer combination, such as Epson Premium Glossy, or one created using ColorMunki print profile, the prints all have a medium to heavy magenta tint or cast.  The effect can be seen before I even print in the Epson Print Preview.  Yet when I soft proof, I don't see this effect.  I suspect the problem lies somewhere in the CMM process, but I can't pin it down.  Any tips or suggestions are appreciated.

    Thank you kindly for your insightful response.  As it turns out, the answer is half correct.  I've found others who'll say the same thing, that double color management will lead to a very magenta result.  I believe this was certainly the case when I first started playing with the settings,  Where I went wrong, is that after I corrected my settings by turning off printer manages color and letting Lightroom do the color management, is that the Epson Print Preview was still showing magenta with certain profiles.  Not wanting to waste more money on paper and ink, I used the preview to gauge whether I was going to get a normal print or not.  Then one day I ignored the print preview's magenta cast as a 'warning' and I went ahead printed the photo anyways.  Because I used a profile that I created with ColorMunki Photo, the picture came out perfect (i.e. a very good match to what I was seeing in Lightoom on my monitor).  The lesson learned is that for judging the final color correctness, the Epson Print Preview can be way off target and your best bet is to ignore it.

  • 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 or Generics, which is better?

    Which is better for serialization <--> de-serialization?
    public class MyClass {
    private Object st;
    public MyClass (Object what) { st = what; }
    public Object get() {return st;}
    out.writeObject(new MyClass("This is a test"));
    Object ob =  in.readObject();
    if (ob instanceof String) {
      Sting result = (String) ob;
    }Or using Generics?
    public static final byte STRING_TYPE = 0x01;
    public class MyClass<T> {
    private T st;
    private byte type;
    public MyClass ( byte type, T what ) { st = what; this.type = type; }
    public T get() {return st;}
    public byte getType() {return type;}
    out.writeObject(new MyClass<String>(STRING_TYPE,"This is a test"));
    MyClass<?> value =  (MyClass<?>) in.readObject()
    if (value.getType() == STRING_VALUE) {
      MyClass<String> str = (MyClass<String>) value;
      Sting result = str.get();
    }Both have unchecked casts (at least according to Eclipse), it is better to cast the generic or just use casts and not use generics? The latter is more complicated but allows more flexibility, but which method is correct?

    CREATE TABLE `login` (
    `username` varchar(40) DEFAULT NULL,
    `password` varchar(40) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `amount` (
    `amountid` int(11) NOT NULL,
    `receiptid` int(11) DEFAULT NULL,
    `loanid` int(11) DEFAULT NULL,
    `amount` bigint(11) DEFAULT NULL,
    `latefee` int(11) DEFAULT NULL,
    `paymentid` int(11) DEFAULT NULL,
    `pid` int(11) DEFAULT NULL,
    PRIMARY KEY (`amountid`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `applicationfee` (
    `applicationfeeid` int(11) DEFAULT NULL,
    `applicationamount` int(11) DEFAULT NULL,
    `applicationfee` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `category` (
    `categoryid` int(11) DEFAULT NULL,
    `categoryname` varchar(40) DEFAULT NULL,
    `categorydescription` varchar(500) DEFAULT NULL,
    `cattype` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `commission` (
    `commissionid` int(11) DEFAULT NULL,
    `bussiness` int(11) DEFAULT NULL,
    `commission` int(11) DEFAULT NULL,
    `pid` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `customer` (
    `cacno` int(11) NOT NULL DEFAULT '0',
    `name` varchar(40) DEFAULT NULL,
    `age` int(11) DEFAULT NULL,
    `cphone` varchar(40) DEFAULT NULL,
    `cmobile` varchar(40) DEFAULT NULL,
    `caddress` varchar(500) DEFAULT NULL,
    `cstatus` varchar(20) DEFAULT NULL,
    `cphoto` longblob,
    `pid` int(11) DEFAULT NULL,
    PRIMARY KEY (`cacno`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `daybook` (
    `closingbal` varchar(40) DEFAULT NULL,
    `date` date DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `extraincome` (
    `categoryid` int(11) NOT NULL,
    `receiptid` int(11) DEFAULT NULL,
    `date` date DEFAULT NULL,
    `amountid` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `employee` (
    `empno` int(11) DEFAULT NULL,
    `empname` varchar(40) DEFAULT NULL,
    `age` int(11) DEFAULT NULL,
    `sal` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `image` (
    `id` int(11) DEFAULT NULL,
    `image` blob
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `loan` (
    `loanid` int(11) NOT NULL DEFAULT '0',
    `loanamt` varchar(40) DEFAULT NULL,
    `payableamount` double DEFAULT NULL,
    `installment` int(11) DEFAULT NULL,
    `payableinstallments` int(11) DEFAULT NULL,
    `monthlyinstallment` varchar(20) DEFAULT NULL,
    `surityname` varchar(20) DEFAULT NULL,
    `applicationfeeid` int(11) DEFAULT NULL,
    `interestrate` float DEFAULT NULL,
    `issuedate` date DEFAULT NULL,
    `duedate` date DEFAULT NULL,
    `nextduedate` date DEFAULT NULL,
    `cacno` int(11) DEFAULT NULL,
    `cname` varchar(20) DEFAULT NULL,
    `pid` int(11) DEFAULT NULL,
    `interestamt` double DEFAULT NULL,
    `pendingamt` float DEFAULT NULL,
    PRIMARY KEY (`loanid`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `md` (
    `mdid` int(11) NOT NULL DEFAULT '0',
    `mdname` varchar(40) DEFAULT NULL,
    `mdphoto` varchar(100) DEFAULT NULL,
    `mdphone` varchar(40) DEFAULT NULL,
    `mdmobile` varchar(40) DEFAULT NULL,
    `mdaddress` varchar(500) DEFAULT NULL,
    PRIMARY KEY (`mdid`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `partner` (
    `pid` int(11) NOT NULL DEFAULT '0',
    `pname` varchar(40) DEFAULT NULL,
    `paddress` varchar(500) DEFAULT NULL,
    `pphoto` varchar(100) DEFAULT NULL,
    `pphone` varchar(40) DEFAULT NULL,
    `pmobile` varchar(40) DEFAULT NULL,
    `pstatus` varchar(20) DEFAULT NULL,
    `mdid` int(11) DEFAULT NULL,
    `mdname` varchar(40) DEFAULT NULL,
    `date` date DEFAULT NULL,
    `nextpaydate` date DEFAULT NULL,
    PRIMARY KEY (`pid`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `partnerinvested` (
    `pid` int(11) DEFAULT NULL,
    `pname` varchar(20) DEFAULT NULL,
    `receiptid` int(11) DEFAULT NULL,
    `date` date DEFAULT NULL,
    `amountinvested` int(11) DEFAULT NULL,
    `latefee` int(11) DEFAULT NULL,
    `amountid` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `payments` (
    `paymentid` int(11) NOT NULL,
    `categoryid` int(11) DEFAULT NULL,
    `particulars` varchar(100) DEFAULT NULL,
    `amountid` int(11) DEFAULT NULL,
    `paymentdate` date DEFAULT NULL,
    PRIMARY KEY (`paymentid`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    CREATE TABLE `receipts` (
    `receiptid` int(11) DEFAULT NULL,
    `paiddate` date DEFAULT NULL,
    `amountid` int(11) DEFAULT NULL,
    `loanid` int(11) DEFAULT NULL,
    `latefee` int(11) DEFAULT NULL,
    `installment` int(11) DEFAULT NULL,
    `cacno` int(11) DEFAULT NULL,
    `cname` varchar(40) DEFAULT NULL,
    `pid` int(11) DEFAULT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

  • How to test and cast an object to a generic

    Hi all,
    my problem is the following:
    I have a list of notifications from a transaction listener of the Eclipse Modeling Framework.
    Each element of that list is of type Notification, but I have to cast it to something else to work with it since it is pretty useless by itself.
    I need to test if it is a certain generic type (+NotifyingListImpl<?>+) but of course I can't use the instanceof test. Is there a way to solve the problem?
    Bear in mind that I googled a lot and tried a lot of solutions without success before asking this question (which I hope it is a piece of cake for an
    java expert :-) )
    As a side problem I don't know the actual type of the generic since I gathered all the information using the Eclipse debug, and the debug
    says my notification is of type NotifyingListImpl$1, I figured out the parameter of that type is ResourceImpl since the inspection of the
    notification's list of fields contains a this$0 of that type. Is my intuition about the Eclipse debug correct?

    I need to test if it is a certain generic type (+NotifyingListImpl<?>+) but of course I can't use the instanceof test.Yes you can:
    if (object instanceof NotifyingListImpl) { ... }
    As a side problem I don't know the actual type of the genericYou can't. It is erased to the lower bound at compile time.
    since I gathered all the information using the Eclipse debug, and the debug
    Is my intuition about the Eclipse debug correct?It has nothing to do with Eclipse debug. The information isn't available. It was erased by the compiler.

  • Type casting in generics 2

    Is there any way to avoid casting in following code using generics.
    public Interface SomeInterface
    public class SomeClass implements SomeInterface
    public class SomeClass1
    public void meth(SomeInterface obj)
    SomeClass cls = (SomeClass) obj;
    }

    why would you want to cast the interface to the concrete class? if SomeClass implements SomeInterface, presumably it's because what your client code is interested in is SomeInterface, that's why we use interfaces. you can't be sure that obj is always going to be an instance of SomeClass, only that it's an instance of SomeInterface. If you could be sure, there'd be no point having the two types
    generics are a non-issue here

  • Generic Observer - Casting problems..

    I'm trying to make a generic observer pattern, modeled after Wadler's book.
    But I get type errors at the lines marked with ?? below, and although I fixed them, don't understand why the original code is wrong - any help please!
    interface Observer<S extends Observable<S,O,A>,
                           O extends Observer  <S,O,A>,
                           A > {
         public void update ( S subject, A arg);
         // public void update ( Observable<S,O,A> subject, A arg);
    abstract class Observable<S extends Observable<S,O,A>,
                                 O extends Observer  <S,O,A>,
                                 A > {
         List<Observer<S,O,A>> obs = new ArrayList<Observer<S,O,A>>();
         boolean changed = false;
        public void          notifyObservers(A a){
             // for ( O o : obs )            // ??
             //    o.update(this,a);          // ??
             for ( Observer<S,O,A> o : obs )
                  o.update((S)this,a );     // Cast??
    }

    Stephan,
    To illustrate the problem with your version and a client;
    The type TestObsGen must implement the inherited abstract method Observer<Thing,TestObsGen,Integer>.update(Observable<Thing,TestObsGen,Integer>, Integer)
    Any insights welcome!
    public interface Observer<
         S extends Observable<S, O, A>,
         O extends Observer<S, O, A>,
         A> {
        public void update(Observable<S, O, A> subject, A arg);
    abstract class Observable<
                   S extends Observable<S, O, A>,
                   O extends Observer<S, O, A>,
                   A> {
        List<Observer<S, O, A>> obs = new ArrayList<Observer<S, O, A>>();
        boolean changed = false;
        public void notifyObservers(A a) {
            for (Observer<S, O, A> o : obs)
                o.update(this, a);
    public class TestObsGen
         implements Observer< Thing, TestObsGen, Integer >
         Thing thing;
         TestObsGen ( Thing t ) {
              thing = t;
              // t.addObserver(this);
         void update(Thing t, Integer count) {
              System.out.println("Count:" + count);
         public static void main(String[] args) {
              Thing t = new Thing();
              TestObsGen test = new TestObsGen(t);
              t.bump();
              // Event received?!
    class Thing
         extends Observable< Thing, TestObsGen, Integer >
         int count;
         void bump() {
              count++;
              // setChanged();
              // notifyObservers();
    }

  • Legal casting in generics

    I'm migrating from 1.4 to 1.5 and have a question about when casting is legal (and workable) in generics. After reading various literature, it seems that erasure removes type information at run time. Yet casting does seem to work. Here is the source of min() in Collections class -
        public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
            if (comp==null)
                return (T)min((Collection<SelfComparable>) (Collection) coll);
    .....Obviously this code works. If erasure removes type info, how do the casts above work?
    More generally, when is casting to generic types allowed and succeed in 1.5 and above?
    And also I'm curious if the compiler generated any unchecked message on this piece of code (I don't see any suppresswarning tag in the source).
    Thanks

    Obviously this code works. If erasure removes type info, how do the casts above work?A generic call is replaced with explicit casts by the compiler:
    public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {
    // becomes (generic type is erased)
    public static Object min(Collection coll, Comparator comp) {
    Number minimum = min(new ArrayList<Number>(), null);
    // becomes (explicit cast added)
    Number minimum = (Number) min(new ArrayList(), null);
    More generally, when is casting to generic types allowed and succeed in 1.5 and above?It is allowed, but it is always an "unchecked" warning. Note that the generic cast is erased, so it can't succeed or fail.
    The explicit cast that the compiler adds (in this case when the method is called) can fail if there are unchecked warnings.
    Note that if a generic is bounded, the generic cast is erased to the bounds (if <T extends Number> then (T) will be (Number), but if that is an illegal cast you get an compiler error:
    // eclipse compiler will also complain Double is final and cannot be extended.
    public <T extends Double> T min(String arg, Number arg2) {
      // error: Cannot cast from String to T
      Double error = (T) arg;
      // warning: Type safety: The cast from Number to T is actually checking against the erased type Double
      // aka it might be an Integer
      Double warning = (T) arg2;
    }

Maybe you are looking for