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!

Similar Messages

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

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

  • Generic and Inheritance, how to use them together?

    Hi guys, I am trynig to design some components, and they will use both Generics and Inheritance.
    Basically I have a class
    public class GModel <C>{
        protected C data;
        public C getData(){return data;}
    }//And its subclass
    public class ABCModel <C> extends GModel{
    }//On my guess, when I do
    ABCModel abcModel = new ABCModel<MyObject>();The data attribute should be from MyObject type, is it right?
    So, usign the netbeans when I do
    MyObject obj = abcModel.getData();I should not use any casting, since the generics would tell that return object from getDta would be the MyObject.
    Is this right? If yes; did someone try to do that on netbeans?
    Thanks and Regards

    public class GModel <C>{
    public class ABCModel <C> extends GModel{public class ABCModel <C> extends GModel<C>{
    ABCModel abcModel = new ABCModel<MyObject>();ABCModel<MyObject> abcModel = new ABCModel<MyObject>();

  • 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

  • Using generics and J2SE together with JSF

    Hi
    Has anybody experience with using JSF together with J2SE 1.5? Especially generics? I would like to use generics and other improvements from J2SE in the model objects.
    Thnaks in advance ... Rick

    JSF 1.1 is specified for J2SE 5, and the new specification (JSF 1.2 and JSP 2.1) does not include generics.
    If you are talking in terms of ValueBindings or MethodBindings, there really isn't any point since the implementation could only make the cast for you; and it would still not be able to garuantee type safety (the only reason to use generics).
    That's not to say you couldn't use generics in your own development, but I don't think you will see generics incorporated into the specification any time soon.
    Jacob Hookom (JSR-252 EG)

  • MacBook Pro and Airport Express = Problem?

    Seem to be having problems when I boot my Macbook it doesn't connect to my airport Express. I have checked my windows laptop and have no issues at all. Also when my macbook goes to sleep sometimes it doesn't connect back up I have to select the SSID and connect up again.
    Tried the usual things changes ssid - channel and so on, I am currently using WEP 128 otptions 802.11g.

    Hi,
    Try:
    1.) System Preferences->Network->Network Port Configurations- Drag Airport to the top of the list, and uncheck ports you don't need.
    2.) System Preferences-Network-Airport and select join Automatic.
    This should solve your problem.

  • Wireless modem and Airport Express.. one at a time

    Recently my internet provider upgraded my old plug in modem to a newer wireless model. Now it seems that the current setting allow communication with only one or the other at the same time. If I want to be online with the wireless modem and send my iTunes music via Airport Express to my sound system, no dice. I have to either click on the modem up in the Airport choices to be online and listen to iTunes through the computer speakers, or go offline to listen to music through the sound system and Airport Express.
    I'm sure I'm just missing something in preferences or settings somewhere.
    Can someone point me in the right direction?
    Thanks, and Happy New Year!

    No ideas?

  • [svn] 3045: Fix FB-13900: Expression Evaluator: 'is' and 'as' expressions return 'Target player does not support function calls'

    Revision: 3045
    Author: [email protected]
    Date: 2008-08-29 10:59:25 -0700 (Fri, 29 Aug 2008)
    Log Message:
    Fix FB-13900: Expression Evaluator: 'is' and 'as' expressions return 'Target player does not support function calls'
    Ticket Links:
    http://bugs.adobe.com/jira/browse/FB-13900
    Modified Paths:
    flex/sdk/trunk/modules/debugger/src/java/flash/tools/debugger/concrete/BinaryOp.java
    flex/sdk/trunk/modules/debugger/src/java/flash/tools/debugger/concrete/PlayerSession.java

    Revision: 3045
    Author: [email protected]
    Date: 2008-08-29 10:59:25 -0700 (Fri, 29 Aug 2008)
    Log Message:
    Fix FB-13900: Expression Evaluator: 'is' and 'as' expressions return 'Target player does not support function calls'
    Ticket Links:
    http://bugs.adobe.com/jira/browse/FB-13900
    Modified Paths:
    flex/sdk/trunk/modules/debugger/src/java/flash/tools/debugger/concrete/BinaryOp.java
    flex/sdk/trunk/modules/debugger/src/java/flash/tools/debugger/concrete/PlayerSession.java

  • How to get the values for checked and unchecked chekboxes

    Hai i have using the checkbox in for loop.
    I need the urgent help from anyone,
    for example in the loop there is having 5 checkbox if i checked 3 of the ckeckboxes and 2 of the checkboxes are unchecked. I need to get the values for checked checkboxes and unchecked checkboxes. Because if i checked the checkboxes, those values need to be inserted into the database. Those for unchecked checkboxes values need to be deleted from the database. Can anyone help me for this
    i am using the following jsp code for this. If anyone can know about this please post me the sample code.
    <form name="confirmcontainer" id="confirmcontainer" method="post" action="submit.jsp">
    <% for(int i=0;i<value.length;i++) {%>
    <tr>
    <td><input name="assigncontainer_chkbox" d="assigncontainer _chkbox" type="checkbox" value="<%=value[0]%>"></td>
    <td class="bottomborder"><div align="center"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><%=value[1]%> </font></div></td>
    <td bgcolor="#FFFFFF" class="bottomborder"><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><%=value[2]%></font></td>
    </tr>
    <% } %>
    <tr><td><input type="submit" name="submit" value="submit"> </td></tr>
    </form>
    Thanks & Regards,
    Tamilvanan

    Hey thanks Alex and Catastrophe for the quick response...
    I'll be sitting with the functional team and reviewing the roles created.
    Thanks for all the help once more
    Regards,
    Akash.

  • If for some reason u have the icon in your task bar (the one with 2 arrows pointing in a circle) just go into mobile me pref...click sync...and uncheck box show status in menu bar.  My question is, I do not have this option. How do I get the sync to stop

    "if for some reason u have the icon in your task bar (the one with 2 arrows pointing in a circle) just go into mobile me pref...click sync...and uncheck box show status in menu bar."
    I do not have the option box to "show status in menu bar"
    I tried the free for a little while Mobile me, and didn't use it, so cancled. I cannot get the sync status roundabout arrows out of my status bar. AND, they keep trying to sync.
    Another issue related with this is that during the time that I tried out Mobile me, I had my ical alarm set to go off every 2 hours. NOW my computer has an ical  pop-up every 2 hours. I cannot find how to stop it.
    Another issue, Yahoo is trying to sync with my computer and I have no idea why or where that one came from.
    Can anyone out there help me please. 

    "if for some reason u have the icon in your task bar (the one with 2 arrows pointing in a circle) just go into mobile me pref...click sync...and uncheck box show status in menu bar."
    I do not have the option box to "show status in menu bar"
    I tried the free for a little while Mobile me, and didn't use it, so cancled. I cannot get the sync status roundabout arrows out of my status bar. AND, they keep trying to sync.
    Another issue related with this is that during the time that I tried out Mobile me, I had my ical alarm set to go off every 2 hours. NOW my computer has an ical  pop-up every 2 hours. I cannot find how to stop it.
    Another issue, Yahoo is trying to sync with my computer and I have no idea why or where that one came from.
    Can anyone out there help me please. 

  • How can I read my incoming emails in one folder?Like I do in Live mail and Outlook express.

    Now we can only read emails in different folders if I am managing multiple email accounts.
    It does not feel so comfortable as we use Live mail and Outlook express.

    '''Unified Inbox for pop and Imap mail accounts:'''
    If you use the Unified folder view, this will show an Inbox with all emails from all accounts, with sub folder Inboxes for the individual Inboxes for the various accounts. Then you can choose to view the collective Inbox or the individual Inbox.
    This method can be chosen simply and quickly.
    * View > folders > Unified
    '''Setting up Pop mail accounts to use Global Inbox.'''
    Pop mail accounts can be set up to use a Global Inbox in Local Folders.
    Imap mail accounts cannot be set up to use Global Inbox, but can use the Unified view.
    To change Pop mail accounts to use Global Inbox, you would need to move all emails into Local Folders Inbox.
    Then change the settings for each pop mail account.
    Tools > Account Settings > Server Settings for the pop mail account
    click on 'Advanced' button
    select 'Inbox for a different account' and 'Global Inbox (Local Folders)
    click on OK
    You need to do this for each Pop mail account.
    Then close Thunderbird. You must do this before downloading anything otherwise the emails may continue to go to the wrong Inbox.
    Wait a few moments for Thunderbird to fully close and then restart Thunderbird.
    Please read more info on global inbox here:
    * http://kb.mozillazine.org/Global_Inbox

  • Receiving messages on 2 iPhones with different numbers but same Apple ID.  Went under Settings Messages and unchecked second phone

    Receiving duplicate messages on iPhones and an iPad, all with different tele#'s but under same Apple ID# ever since upgrade to 7.0.4.  Went under SETTINGS>MESSAGES>SEND & RECEIVE and unchecked all but that particular iPhone tele# and Email address.  Still reverts back to same problem,  Any further suggestions to resolve?

    Visual voicemail is a carrier feature, contact your cell phone provider and see if it is set up for you to use.

  • How do I get albums out of "compilations'?  On one of my machined I can go to individual songs, "get info" and uncheck "part of a compilation", but that does not work on my office machine.  I would also like to be able to do this in  a group for an album,

    I don't know how so much of my music got lost by being labled "compilations"?  I would like to go back and catagorize it as it should be but the screens are gray and will not let me alter them as to the catagory I wish them to be in (or even the genere they are already labled?  On my home machine I can (by individual song) "get info and uncheck "part of a compilation" and when this is finished the album goes to the genere as it is listed?  Frustrating bit of hous keeping.  Help and Thanks  Chuck

    The Get Info. fields show up gray if the files is locked and iTunes knows it can't edit the file. Make sure the files are not marked as read only and, if necessary grant both your account and system full access to all files and subfolders of your media folder.
    You can set Part of a Compilation for multiple tracks from the Options tab of Get Info.
    See Grouping tracks into albums for tips on getting iTunes organized.
    tt2

  • How to Set Up Time Capsule With Airport Extreme and Airport Express

    Just got a new 1TB Time Capsule. I want it to be the main base station for my network. I already have a network set up with an older Airport Extreme base station and an Airport Express to extend it. I am thinking that rather than setting up the Time Capsule to "join" the old network, the best approach is to disconnect the Airport Extreme and Airport Express and reset them. Then set up the Time Capsule as a brand new network and bring the reset Aiport Extreme and Express onto the new network as if my original network never existed.
    Is that the right approach or am I complicating it? Can I just join the Time Capsule to the existing network and still make it the main base station for the network?

    evelK wrote:
    Just got a new 1TB Time Capsule. I want it to be the main base station for my network. I already have a network set up with an older Airport Extreme base station and an Airport Express to extend it. I am thinking that rather than setting up the Time Capsule to "join" the old network, the best approach is to disconnect the Airport Extreme and Airport Express and reset them. Then set up the Time Capsule as a brand new network and bring the reset Aiport Extreme and Express onto the new network as if my original network never existed.
    Is that the right approach or am I complicating it? Can I just join the Time Capsule to the existing network and still make it the main base station for the network?
    I'd first use AirPort Utility to "Save a Copy As" of your AirPort Extreme settings. Then disconnect it, connect the Time Capsule in its place, and use AirPort Utility's "Import" function to read those settings. (Both of those functions are under AirPort Utility's "File" menu.) You may have to adjust a few settings. Once you have the Time Capsule working as you want, you can reconfigure your AirPort Extreme unit as you wish.

Maybe you are looking for