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;
}

Similar Messages

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

  • Cast a generic object

    Hi how do you cast a generic object.
    For example I have a class GenericModel which can be either a movie or a director however when I wish to print out any awards that either a director or a movie has, I need to cast a generic variable (gM) to either a movie or a director something like this ...
    try {
    GenericModel d = (Director) gM;
    } if that fails do this{
    GenericModel m = (Movie) gM;
    }catch (Exception e){
    Or any other way that works.
    most appreciated

    Huh? I don't see why you necessarily need to cast anything and certainly not to base types such as Director or Movie.
    Also, the "try and if it fails try something else' pattern can be grossly inefficient.
    I wish to print out any awards that either a director or a movie hasThen your Director and Movie objects both need a printAwards() method; they also need to be sub-classes of a common class (or implement a common interface) that has all the behaviors you want to be in common.
    If that common class is GenericModel, then you would merely do:
      gM.printAwards();If that common class is something else, lets call it FilmObject, then you would need to cast your gM object to execute printAwards(), as so:
    if ( gM instanceof FilmObject )
      ( (FilmObject) gM).printAward();
    }This is really more of a basic Java issue that has nothing to do with JDBC or transactions; if you have followup questions, please ask them in another forum, not here.

  • 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

  • How to get an exception when casting a generic collection?

    Hi,
    I have a bit of code that looks more or less like this:import java.util.ArrayList;
    import java.util.Collection;
    public class CollectionTest {
         public static void main (String[] args) {
              try {
                   get (Float.class);
              } catch (ClassCastException e) {
                   System.err.println ("Oops");
                   e.printStackTrace (System.err);
              try {
                   Collection<Short> shorts = get (Short.class);
                   for (Short s : shorts) {
                        System.out.println (s);
              } catch (ClassCastException e) {
                   System.err.println ("Oops");
                   e.printStackTrace (System.err);
              try {
                   Collection<Number> numbers = get (Number.class);
                   for (Number number : numbers) {
                        System.out.println (number);
              } catch (ClassCastException e) {
                   System.out.println ("Oops again");
                   e.printStackTrace (System.err);
         public static <T> Collection<T> get (Class<T> clazz) {
              Collection<T> ret = new ArrayList<T> ();
              if (clazz == String.class) {
                   ret.add (clazz.cast ("Test"));
              } else if (clazz == Integer.class) {
                   ret.add (clazz.cast (Integer.valueOf (1)));
              } else if (clazz == Double.class) {
                   ret.add (clazz.cast (Double.valueOf (1.0)));
              } else if (clazz == Float.class) {
                   ret.add (clazz.cast ("Bug")); // Bug here, blatent
              } else if (clazz == Short.class) {
                   ret.add ((T) "Bug"); // Bug here, latent
              } else if (clazz == Number.class) {
                   ret.addAll (get (Integer.class));
                   ret.addAll (get (Double.class));
                   ret.addAll (get (String.class)); // Another bug here, latent
              return ret;
    }Obviously this doesn't compile as-is, I have to add 3 casts towards the end. Then when I add the casts and run the program I discover I have several bugs, some of which are fail-early and some of which lie hidden until the further away from the bug Since I have the type-token, I use it to check the simple cast, but is there any way I can get a failure more or less at the point where the dodgy Collection cast is made?

    OK, sorry not to be clear. My example code is meant to crash on the erroneous casts - clearly a String cannot be cast to a Float, nor a Short. My point is that in one case the code crashes at the point where the cast is made and in another case the code crashes later on. What I want to achieve is this early failure in case of buggy code. Here is a shorter example:import java.util.ArrayList;
    import java.util.Collection;
    public class CollectionTest {     
         public static <T> Collection<T> get (Class<T> clazz) {
              Collection<T> ret = new ArrayList<T> ();
              if (clazz == String.class) {
                   ret.add (clazz.cast ("Test"));
              } else if (clazz == Integer.class) {
                   ret.add (clazz.cast (Integer.valueOf (1)));
              } else if (clazz == Double.class) {
                   ret.add (clazz.cast (Double.valueOf (1.0)));
              } else if (clazz == Number.class) {
                   ret.addAll ((Collection<? extends T>) get (Integer.class));
                   ret.addAll ((Collection<? extends T>) get (Double.class));
                    // This is a bug, but how can I get an exception at this point?
                   ret.addAll ((Collection<? extends T>) get (String.class));
              return ret;
    }If I mistakenly write this code it will compile (with the addition of the appropriate casts). However, my code is buggy and will fail when the user of the collection receives a String when he is expecting a Number. My question is, how can I get my code to fail where I make the erroneous cast? If you look at the code I originally posted I have two casts of the String "Bug", one of which is done by (T) and the other is clazz.cast. The first example fails late and the second fails early - it is this early failure that I would like to achieve, in the case of buggy code, in my example above.
    Am I making sense yet?

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

  • How to cast an object to a class known only at runtime

    I have a HashMap with key as a class name and value as the instance of that class. When I do a 'get' on it with the class name as the key, what I get back is a generic java.lang.Object. I want to cast this generic object to the class to which it belongs. But I don't know the class at compile time. It would be available only at runtime. And I need to invoke methods on the instance of this specifc class.
    I'm not aware of the ways to do it. Could anybody suggest/guide me how to do it? I would really appreciate.
    Thanks a lot in advance.

    Thanks all for the prompt replies. I am using
    reflection and so a generic object is fine, I guess.
    But a general question (curiosity) specific to your
    comment - extraordinarily generic...
    I understand there's definitely some overhead of
    reflection. So is it advisable to go for interface
    instead of reflection?
    Thanks.Arguments for interfaces rather than reflection...
    Major benefit at run-time:
    Invoking a method using reflection takes more than 20 times as long without using a JIT compiler (using the -Xint option of Java 1.3.0 on WinNT)... Unable to tell with the JIT compiler, since the method used for testing was simple enough to inline - which resulted in an unrealistic 100x speed difference.
    The above tests do not include the overhead of exception handling, nor for locating the method to be executed - ie, in both the simple method invocation and reflective method invocations, the exact method was known at compile time and so there is no "locative" logic in these timings.
    Major benefit at compile-time:
    Compile-time type safety! If you are looking for a method doSomething, and you typo it to doSoemthing, if you are using direct method invocation this will be identified at compile time. If you are using reflection, it will compile successfully and throw a MethodNotFoundException at run time.
    Similarly, direct method invocation offers compile-time checking of arguments, result types and expected exceptions, which all need to be dealt with at runtime if using reflection.
    Personal and professional recommendation:
    If there is any common theme to the objects you're storing in your hashtable, wrap that into an interface that defines a clear way to access expected functionality. This leaves implementations of the interface (The objects you will store in the hashtable) to map the interface methods to the required functionality implementation, in whatever manner they deem appropriate (Hopefully efficiently :-)
    If this is feasible, you will find it will produce a result that performs better and is more maintainable. If the interface is designed well, it should also be just as extensible as if you used reflection.

  • Mixing generic and concrete classes

    I am going over the generics tutorial by Gilad Bracha offered by Sun. Something strikes me as wrong
    Collection c;
    Collection<Part> k = c; //compile-time unchecked warning
    Collection<Part> k = (Collection<Part>) c; //compile-time unchecked warningFor me, the first unchecked warning is mildly acceptable, but my honest opinion is it should be an error not a warning. Isint this effectively an automatic narrowing cast? I personally like my cases to be inside of (), and not hidden. I could be wrong.
    The second unchecked warning however should not even be given. If the 2nd warning is acceptable, then why not flag all casts as 'unchecked warnings?'
    I have a feeling this has to do with this 'erasure' stuff and the resultant class files. I would appreciate any light you could shed on this for me.

    Well Java is really a hobby for me and i end up doing other stuff for several months at a time. And now I am back into Java. I'm finding that I usually do it in the fall and winter, strange..
    Plus 1.5 is so exciting, I'm like a baby all over again with so much to learn!
    I am learning that generics is all compile-time, so I kind of understand that there is really no such thing as casting a generic type. Or that it makes no sense since casting and generics live in different "times" for lack of a better term.
    I think i get it. The second would give the false impression that a cast is actually taking place, and would thus pollute the notion of casting with this fake cast. And the first is not a warning about that line in particular, but a warning about the fact that you are taking your type-safety into your own hands when you subvert the system in this fashion. Which also applies to the second. In fact the cast is immaterial.
    OK, I see now how they are the same thing. But why is generic casting even allowed if its meaningless?

  • How to cast an array object to array of string

    * Can someone please tell me why SECTION 3 causes a cast
    * exception?
    * What I am really trying to do is put Strings into a vector and
    * return them as an array of String with a line like:
    *     return (String[])myVector.toArray();
    * How to do this?
    * Thank You!
    public class CastArrayTest
         public static void main(String args[]){
              //SECTION 1: This works
              String[] fruits = {"apple", "banana"};
              Object[] objs = (Object[])fruits;
              String[] foods = (String[])objs;
              for (int i = 0 ; i < foods.length ; i++){
                   System.out.println(foods);
              //SECTION 2: this works too
              Object anObj = new Object();
              String aString = "ok";
              anObj = aString;
              String anotherString = (String)anObj;
              System.out.println("word for single obj is " + anotherString);
              //SECTION 3: this causes cast exception at line
              // String[] strings = (String[])stuff
              Object[] stuff = new Object[2];
              String a = "try";
              String b = "this";
              stuff[0] = a;
              stuff[1] = b;
              String[] strings = (String[])stuff;
              for (int x = 0 ; x < strings.length ; x++){
                   String s = strings[x];
                   System.out.println("the string is " + strings[x]);

    I understand all replies so far, but from my
    understanding, objects are passed by reference No, they're not. Rather, object references are passed by value.
    Object obj = new Object();
    String a = "pass me by reference";
    Object anotherObj = (Object)a; // this explicit cast is not necessary
    String anotherString = (String)anotherObj; // this cast works because the object in question is a String
    There's no passing in that code, so I'm not sure where that even came from. However, that works because it's all legal casting.
    works as I think it should, and does, and futhermore
    String[] cast to Obj[] cast to String[] works also...Because the object you're casting actually is a String[].
    so why not if Obj[] to String[] Because String[] is not a subclass of Object[]. That's just how the language is specified.
    futhermore if they are
    all string...Again, this has no bearing on the type of the array object.
    I saw hot to cast array to String[] and wondered if
    this is real cast or calls the toString method...It's a real cast.
    but most importantly, does this mean if I have a
    vector of Strings and want to get them as an array of
    strings, I have to loop through the Obj[] (or vector)
    and cast each to (String)...just to get them as an
    array of String[]....No, zparticle's code can do that.

  • Downcasting a subclass of a concrete generic

    Hi--
    Been puzzling over this one for quite awhile, and I still can't figure it out. I'm trying to downcast a generic type to a subclass of a concrete type. Now admittedly that's messy and I'd like to refactor, but I'm still puzzled. Take the following code:
    public class Test1<T> {
        protected final T obj;
        public Test1(T obj) {
         this.obj = obj;
        public static void main(String[] args) {
         Test1<?> testObj = new Test2("hello");
         System.err.println("Calling a method: " + ((Test2) testObj)).aMethod());
    public class Test2 extends Test1<String> {
        public Test2(String obj) {
         super(obj);
        public String aMethod() {
         return obj;
    }This fails to compile, saying that Test1<capture of ?> isn't convertible to Test2.
    Now suppose I change to the following:
    public class Test1<T> {
        protected final T obj;
        public Test1(T obj) {
         this.obj = obj;
        public static void main(String[] args) {
         Test1<?> testObj = new Test2<String>("hello");
         System.err.println("Calling a method: " + ((Test2) testObj).anotherMethod());
    public class Test2<T extends String> extends Test1<T> {
        public Test2(T obj) {
         super(obj);
        public String anotherMethod() {
         return obj;
    }Here all I've done is add a parameter to the Test2 type that gives the same information available in item 1. In this case, however, it compiles and runs fine.
    Even more oddly, the following also works and does not produce any warnings:
    public class Test1<T> {
        protected final T obj;
        public Test1(T obj) {
         this.obj = obj;
        public static void main(String[] args) {
         Test1<?> testObj = new Test2("hello");
         System.err.println("Calling a method: " + ((Test2) ((Test1) testObj)).anotherMethod());
    public class Test2 extends Test1<String> {
        public Test2(String obj) {
         super(obj);
        public String anotherMethod() {
         return obj;
    }So essentially the system is ok as long as I cast the generic type to a raw type, and then downcast to the subclass of the concrete type... but I can't do the cast directly?
    My feeling is that Java is being a little overly touchy about trying to prevent casting to a concrete type-- in the case where the type you're trying to cast to is itself not generic, shouldn't that be allowed? Or am I missing something subtle about how the generics work?

    Correct me if I'm wrong, but I think this may be your problem:
    public class Test2 extends Test1<String> {
    }This means that Test2 is a subclass of Test1<String> -- not Test1<?>. Here's why.
    If we "expand out," say, Test1<Integer> and Test1<String>, we get the following:
    public class Test1String {
       protected final String obj;
       public Test1String(String obj) {
       this.obj = obj;
    public class Test1Integer{
       protected final Integer obj;
       public Test1Integer(Integer obj) {
       this.obj = obj;
    }Now, it's easy to see that inheriting from each of these classes yields completely different results. Once you've parameterized a class, it becomes a completely different beast. Sooo, saying that
    Test1<?> testObj = new Test2("hello");could be the same thing as saying (since ? means any parameter), in our expanded form,
    Test1Integer testObj = new Test2("hello"); //aka, a new Test1String
    //or Test1Object, Test1MyComplicatedType, whateverwhich is clearly not allowed, since all the fields would be of a completely different type.
    I hope this helps!

  • Generics and clone().

    I am trying to do
    ArrayList<Integer> tempList = (ArrayList <Integer>) list.clone();but I get the unchecked warning. list is defined as ArrayList<Integer> list.
    Basically, I am trying to cast the clone of list so that list remains unchanged by my method, so I am creating a templist using the clone. I am confused with respect to how to go about doing this cast using generics.
    Thanks in advance.

    This version gives the warning:
    public class Test {
        public static void main(String[] arguments) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            ArrayList<Integer> clone = (ArrayList<Integer>)list.clone();
    }However, Drake_Dun is right, you probably want to copy the
    list rather than cloning it. If you insist on using clone without a
    warning, you loose the type information:
    public class Test {
        public static void main(String[] arguments) {
            ArrayList<Integer> list = new ArrayList<Integer>();
            ArrayList<?> clone = (ArrayList<?>)list.clone();
    }

  • Overloading & Cast &Type Save?

    Here I use final bounds, therefore ignore cast warnings
    and test overloading and inference(<- do not work)
    My question: Is this considered type-save? public class DoW {
      public static final String[] DAY_NAME=
           {"Su","Mo","Tu","We","Th","Fr","Sa"};
      private int wd;
      public DoW(int day,int month, int year) {
        // just for fun
        if (month<3) { month= month+12; year--; }
        wd= (day+ 2*month+ 3*(month+1)/5+ year+
             year/4-year/100+year/400+1)%7;
      public <T extends String> T getDoW()  { return (T)DAY_NAME[wd]; }
      public <T extends Integer> T getDoW() { return (T)new Integer(wd); }
      public static void main(String[] args) {
        DoW dow= new DoW(20,2,2005);
        System.out.println(dow.<String>getDoW()+" #"+dow.<Integer>getDoW());
    }

    I do not argue about sense, let me tinker please!
    1. As String/Integer are final they can be used to fool
    the compiler and get overloading on return types as a free lunch.
    2. See reply Gafter to "Usafe casting with generics"
    The compiler warns precisely when it cannot generate code to fully check the cast at runtime.Really? I doubt that, as Sun even ignores it's own compiler warning sometime.
    If these two warnings are contrary to the fact that this is type save,
    no one will care too much about warnings, as he might think
    "my code is also Sun-type save".
    This would be a (tiny?) disaster for Generics, as it depends on the fact
    that only "warning-less" code can be used as generic building blocks.
    3. If finals make a sense in bounds the compiler should not ignore that.

  • A script to pick up song lyrics from the web - feedback

    Below is a PC implementation of this script written by Chris Schull which uses google to grab the lyrics of the selected song in iTunes and add them to the tags for the song.
    Enjoy Andrew's first go at converting an Applescript to .net for the PC. I guess it is written in C++ since the file he gave me is .cs ?
    using System;
    using iTunesLib;
    using System.Net;
    using System.IO;
    using System.Collections;
    namespace AJCOWLEY
    /// <summary>
    /// Provides Windows .Net methods for interacting with iTunes.
    /// version 0.1 (this version) gets the lyrics for the currently playing track.
    /// </summary>
    public class myTunes
    IiTunes iTunesApp;
    const string baseurl = "http://www.google.com/search?q=site:searchlyrics.org-download";
    public myTunes()
    iTunesApp = new iTunesAppClass();
    //Currently am only supporting one method: so go to it.
    //Supply the current track playing. In future could loop around
    // a playlist or selected tracks and get lyrics for all of them.
    // easy enough to add when it is working reliably for one..
    get_lyrical(iTunesApp.CurrentTrack, true);
    static void Main()
    //Instantiate an instance of the main class
    myTunes _this = new myTunes();
    * get_lyrical:
    * First method developed for the myTunes application.
    * Will get the lyrics for a given track
    void get_lyrical(iTunesLib.IITTrack t, bool overwrite)
    if ( (t != null) && ( ( t.Kind == ITTrackKind.ITTrackKindCD ) || (t.Kind == ITTrackKind.ITTrackKindFile )))
    //Cast the generic track pointer
    // to a pointer that supports lyrics
    IITFileOrCDTrack f = (IITFileOrCDTrack) t;
    //Get the current lyrics
    string l = f.Lyrics;
    //Check if okay to overwrite
    if ( (l == null) || ( l.Length == 0 ) || (overwrite == true))
    f.Lyrics = get_lyrics(f.Artist, f.Name );
    * get_lyrics:
    * Asks google to search a lyric website, and loops through
    * each of the google hits. Each hit is opened and examined to see if
    * it contains lyrics within predetermined delimters.
    string get_lyrics(string Artist, string TrackName)
    //Setup the url to be searched. remove parantheses and spaces from arguments
    string url = baseurl+ fixup(Artist) +" lyrics " + fixup(TrackName);
    string google_response=WebQuery(url);
    * Loop through each google hit, get the URL, open the page, strip out the lyrics
    * until lyrics != null
    foreach( string hiturl in getgooglehits(googleresponse))
    //launch the hit
    //get responses in between the values "<font" and "</font>"
    //then home in on the first ">" character.
    string hitpage = WebQuery(fixup(hiturl));
    hitpage=TextBetween(hitpage,"<font","</font>");
    //Strio off the "" text
    hitpage=hitpage.Substring(hitpage.IndexOf(">")+1);
    //Strip off the "" text
    hitpage=hitpage.Substring(0,hitpage.Length - 7);
    //Strip off html newline breaks
    string lyrics = clearHTML(hitpage);
    if (lyrics.Length > 0 )
    return hiturl":n"lyrics;
    return "";
    string clearHTML(string text)
    string clean_text="";
    bool kill=false;
    foreach (char c in text)
    if (c=='<') kill = false;
    return clean_text;
    * WebQuery:
    * Open a web page and return the results as a string using System.Net
    * N.B. The GetResponse method doesnt seem to like going through proxy servers.
    * and yes, this should be in a class of its own (sic)
    string WebQuery(string url)
    WebResponse myResponse=null;
    StreamReader readStream=null;
    try
    // Initialize the WebRequest and get the Webresponse handle
    WebRequest myRequest = WebRequest.Create(url);
    myResponse = myRequest.GetResponse();
    // Read through the WebResponse.
    Stream receiveStream = myResponse.GetResponseStream();
    // Pipes the stream to a higher level stream reader with the required encoding format.
    readStream = new StreamReader (receiveStream, System.Text.Encoding.UTF8 );
    string text= readStream.ReadToEnd();
    return text;
    catch
    return "";
    finally
    // Free up the resources.
    if ( readStream != null) readStream.Close();
    if (myResponse != null) myResponse.Close();
    /* Loop throught the results using the <div> tags and http/html as markers
    * to indicate where the results are
    ArrayList get_googlehits(string google_results)
    string text= google_results;
    ArrayList s = new ArrayList();
    string part;
    while ( text.Length > 0)
    //First zone in on the text between the div tags
    part=TextBetween(text,"","");
    //Now zone in on the url itself. The url will start with http and end in .html
    part=TextBetween(part,"http",".html");
    if ( part.Length == 0 )text=""; //reached end of the line
    else
    //prepare string for the next go around by stripping off
    //the bit we have already looked at.
    text=text.Substring(text.IndexOf(""));
    //Add hit to the array
    s.Add(part);
    return s;
    //Simple function to extract text between ( and including) two
    //separators.
    //Ideally this would be a class extension of "string"
    string TextBetween(string s, string spat, string epat)
    int startpos = 0, len;
    string tmp;
    if ((s==null) || (s.Length==0))
    return "";
    startpos=s.IndexOf(spat,startpos);
    if (startpos== -1 )
    return "";
    tmp=s.Substring(startpos);
    len=tmp.IndexOf(epat);
    if (len==-1)
    return "";
    else
    tmp=tmp.Substring(0,len+epat.Length);
    return tmp;
    //Replace spaces with + and remove parentheses
    string fixup(string s)
    return s.Replace(" ","+").Replace("(","").Replace(")","");
    } //end of class declaration
    }//end of Namespace

    Otto42 has a multi-script utility that will do just this function.
    See here for individual functions: http://ottodestruct.com/blog/2005/10/20/itunes-javascripts/
    Or get his 'QuickScripts.zip' multi-script utility: http://ottodestruct.com/blog/category/geekery/programmery/

  • Error in proposed Collections.sort signature

    (A very long time ago I've send a note on this to the jsr comment list, but unfortunately I never got a reply nor did I notice a bug report. Therefore I propose the change again here).
    The signature of the Collections.sort method is very limiting:
      static <T> void sort(List<T> list, Comparator<T> c);This signature requires you to pass a Comparator that is parameterized with exactly the same type as the items in the List. However, often Comparators can be implemented more generic. The signature doesn't allow this. The only requirement for the sort algorithm is however to pass a Comparator that is able to compare the items in the List.
    This requirement is expressed by the following signature:
      static <T, E extends T> void sort(List<E> list, Comparator<T> comparator) The items in the List are now allowed to be more specific. Because I don't want to cast in Generic Java code I've implemented a tiny workaround:
      public static <T, E extends T> void sort(List<E> list, Comparator<T> comparator) {
        Collections.sort(list, new ComparatorWrapper<T, E>(comparator));
      private static class ComparatorWrapper<T, E extends T> implements Comparator<E> {
        private Comparator<T> _comparator;
        public ComparatorWrapper(Comparator<T> comparator) {
          super();
          _comparator = comparator;
        public int compare(E o1, E o2) {
          return _comparator.compare(o1, o2);
      }This proves the correctness of the new signature. This also proves that you have to be very careful in chosing a signature. I've been working with Generic Java for some years now, but I'm still making the same mistake now and then ...

    This will be fixed in a novel and interesting way in the new spec for GJ -- stay tuned! (I think mid-May/late-May is the expected timeframe for this.)

  • How many elements in an array?

    Sounds like a simple question, right?
    Apparently not.
    LV 2010
    I have a huge data structure, stored in DataLog files (thousands of them).
    I want to convert this structure to Name/Value pairs ("Operator_Name", "Joe Smith"), for use in a TDMS file.
    The structure is a cluster, with various clusters inside that, and inside those are DBLs, strings, BOOLs, other clusters, arrays, you name it.
    My strategy is to obtain the CONTROLS[ ] property of the outermost cluster and call this VI.
    The VI processes each control, decoding what type it is and handling it accordingly.
    It works fine for STRINGs, NUMERICs, ENUMs, BOOLEANs, COMBOBOXes, TIMESTAMPS, and CLUSTERs.
    For those simple ones, I use the LABEL.TEXT as the NAME and get the value (based on what type it is) as the VALUE.
    For a CLUSTER, I get the CONTROLS[ ] array of the cluster and call myself recursively, to handle all the elements within the sub-cluster.
    That all works fine.
    But to handle an ARRAY, I'm stumped.
    Attached is the code showing the case for an ARRAY.
    What I'm doing is getting the CLASS NAME of the current control.
    I LEGALIZE the label name (turn spaces into underscores, and maybe other special handling later).
    For an ARRAY, I cast the generic CTL reference into an ARRAY reference, and get its VALUE.
    I want to loop over each element of the array, and modify the name by the index number, and process each element.
    There are arrays of STRINGS, arrays of DBLs, arrays of CLUSTERs - all types.
    The question is - how many array elements are there?
    The constant "10" in this diagram is a dummy - just there to see if it works.
    it does work, except that I get 10 sets of answers, whether the real array has 2 or 20 elements.
    I thought the array's VALUE would be an ARRAY of VARIANTs, but no - it's a single VARIANT.
    I can't use VARIANT to DATA on the array's VALUE - I don't know what TYPE the array is.
    I thought maybe the ARRELEM refnum would be NIL if I was past the end, but that's not the case - there's only one refnum for any array element, whether it exists or not.
    If I check for errors, it complains that I cannot set the INDEXVALS property of a strict typedef array, even though it works just fine.
    If there was a method to SELECT ALL on the array, I could use the SELECTION SIZE to figure out how many elements there are, but I see no such method.
    The NUMBER OF ROWS / COLUMNS refers to the number of VISIBLE rows/columns, and has nothing to do with how much data is present.
    So... How do I find out how many elements are in the array?
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

    The ArrElem reference property is not a reference to any particular element of the array. 
    On the contrary, it is a reference to the element addressed by the current ARRAY INDEX(es).
    That's why my code above can read out the values for element 0, element 1, etc.  I've verified that this works.
    There is only one set of PROPERTIES for the array elements; if you use the ArrElem refnum to set a background color of blue, then ALL elements turn blue, but you can obtain the VALUE of a given element by setting the ARRAY INDEX(es) and accessing via the ArrElem.
    I was thinking that maybe LabVIEW did a trick by setting this to NIL to indicate "no such element", but that's not the case.
    In any case, the question remains: How do I determine how many elements there are?
    The VALUE of the array is a variant: just what is in that package?
    As I said, I don't see how to use VARIANT TO DATA; I don't know what kind of data it is.
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

Maybe you are looking for

  • Flattening gradients with transparency issues * CS4

    Hi guys, I've invested far too much time trying to figure this out. I have three squares (two gradients and one white) on different soft light values intersecting each other. I need to flatten this transparency for production purposes and I'm getting

  • WPF Styles and WPF Crystal Reports viewer

    Hi, We are currently developing a WPF application which will utilize Styles created with Expression Blend. Our environment is VS2010 SP1 and Crystal Reports for VS2010 SP2. We want to design our reports with Crystal Reports but we don't seem to find

  • Oracle Timing

    Hi, Do you know how to record the process time for each query? especially spatial query in Oracle? Any system functions? Thank you so much! Xiong

  • What Adobe I have in my computer?

    I have a program that is requesting in order to open to use Adobe 9+

  • Presonus Faderport -

    Can I use the Presonus Faderport with my Macbook Pro running Logic Pro 9?  I see mixed answers here.  Is there maybe another similar controller out there? Happy New Year to all and thanks in advance!