When should object casting be used?

Hi,
just wondering something. Saw there that returning objects from methods and downcasting the returned object is bad. When should casting be used? I currently have a program that has an object that contains a HashMap as a field. When I try retrieve objects from the HashMap using the relevant key, I have to cast them to what they were originally! Is this bad programming practice or is it the only way to do things?
Thanks.
// example of retrieving object from key
dbDirectory = (String)dbInfo.get("dbDirectory");

LeWalrus wrote:
Hi,
just wondering something. Saw there that returning objects from methods and downcasting the returned object is bad. When should casting be used? I currently have a program that has an object that contains a HashMap as a field. When I try retrieve objects from the HashMap using the relevant key, I have to cast them to what they were originally! Is this bad programming practice or is it the only way to do things?
Thanks.
// example of retrieving object from key
dbDirectory = (String)dbInfo.get("dbDirectory");
Before generics, this was a perfectly acceptable practice. Generally speaking, you use type-casting when the compiler is unable to ensure the type validity at compile-time, but you know it is correct, so you supply the extra information to the compiler so it knows everything is correct. Sometimes you need to circumvent the strong type-checking part of the language for flexibility, but this is something that should be used very sparingly.
Now it would be better to use generics so that the compiler will know at compile time that the values in your map are Strings, instead of just Objects.

Similar Messages

  • When should a DSO be used?

    When should a DSO be used?

    Hi surya,
    1.Mainly ODS is used to store detailed level of data.
    2. Getting teh data overwrtten for key fiedls instead of appending.
    3. Delta functionality because of the Change log table.
    4.All Datasources in ECC will not support for Delta. In such scenarios will go for DSO before cube, as DSO has Overwrite functionality.
    If datasource does not support Delta, we can do full update to DSO and from there we can do Delta Update to Cube. We can maintain change log of each record in DSO,as it has chanege log table.
    Here is the detail of Type of DSO in BI,
    DataStore object types:
    Standard DataStore object
    Data provided using a data transfer process
    SID values can be generated
    Data records with the same key are aggregated during activation
    Data is available for reporting after activation
    Write-optimized DataStore object
    Data provided using a data transfer process
    SID values cannot be generated
    Records with the same key are not aggregated
    Data is available for reporting immediately after it is loaded
    DataStore object for direct update
    Data provided using APIs
    SIDs cannot be generated
    Records with the same key are not aggregated
    And you can find more information / examples on this topic at:
    http://help.sap.com/saphelp_nw04s/helpdata/en/F9/45503C242B4A67E10000000A114084/content.htm

  • When should we prefer to use LinkedList

    when should we prefer to use LinkedList ?

    i have read some where related to java performance...stating that
    http://www.java-performance-portal.org/modules.php?name=News&file=article&sid=8
    The ArrayList is quite fast for accessing the elements in direct or random order, but the pure sequential use the LinkedList might be concerned as the right List for an application. The Vector provides snchronized access to its elements and is a slower than the ArrayList.
    what does it means exactly -------
    accessing the elements in direct or random order or sequential ??

  • When should we prefer to use JSF

    we work on web based applications in servlets and jsp .
    this is my first message in this forums...
    since nowadays i come across hearing JSF..i am interested to clarfiy that weather it is used along with jsp
    or it would replace jsp....
    say
    index.jsp----->index.jsf

    In the project I am working on we have adopted the convention of using the .jsf extension for JSPs that contain JSF tags (mainly forms) and .jsp for regular JSPs. This helps to differentiate the pages that are displayed via the Faces servlet and the distinction can be useful when writing build scripts or using other automated tools.
    -- Keith

  • Invalid table name  error when updating object in collection using SQL

    Hi,
    I have pl/sql code where I am selecting a object from a collection using sql select query. I am processing this record and now I want to update the collection with the new object. ie. ensure that the object that was fetched be removed and this new one be added.
    considering my_ot is the object type and my_tt is the table type.
    DECLARE
    my_col my_tt;
    my_col1 my_tt
    my_var my_ot;
    my_var2 VARCHAR2(10);
    BEGIN
    // populating my_col1 with select query
    //populating my_col with select query
    FOR my_col1.FIRST .. my_col.LAST LOOP
    //populating my_var2
    BEGIN
    SELECT my_ot(c.field1, c.field2 ,c.field3) INTO my_var FROM TABLE(my_col) c WHERE c.field3 = my_var2
    //processing the field my_VAR
    UPDATE TABLE(my_col) c SET c.field1 = my_var.field1 , c.field2 = my_var.field2 , WHERE c.field3 = my_var.field3;
    EXCEPTION WHEN NO_DATA_FOUND
    my_col.EXTEND;
    my_col(my_col.LAST) := // new my_ot object
    END;
    END LOOP;
    Here, when compiling the update query is not being compiled. I am getting a error 'invalid table name'. Is there any way to modify an object in the collection without knowing its index?
    If not, is it possible to find the index of a object in the collection in select query?
    Thanks in advance
    Paddy

    Hi,
    Is there any way to find the index of a object in the collection? Then I will simply replace the object at that index, right!
    Thanks
    Paddy

  • When should this file be used?

    Hi!
    I have left this forum for a long while, but now I am back.
    Sorry, may I start with a question?
    I don't know when we should we use Context Listeners?
    Please help if you could!

    Do you mean ServletContextListener? Look it up in the J2EE API documentation (javax.servlet.ServletContextListener).
    A ServletContextListener is called when the context of the servlet it belongs to is created or destroyed, i.e. when the web application is started up or shut down. If you need to initialise or cleanup things for your web application, you could do it with a ServletContextListener.

  • When should mapping.getAttribute() be used in Struts?

    and why do we need attribute in Action mapping when we already have form bean?

    // you posted in the FCPX-forum intentionally? //
    pheewwww - where to start?
    'film'is a year long study, very academic.
    plus, due to about a 100 years in use, film'language' is part of public concious - there are perhaps 'rules' or common agreements, but an artist will break rules - for a reason.
    In MY simple understanding: a cross-dissolve 'combines', a fade-to-black/-white seperates.
    but that has to been seen - as in any language - in context.
    a dissolve could mean 'meanwhile'.
    a fade has, imho, some 'stop'.
    or some 'and now to something completely different!"
    (Python did NOT dissolve nor fade http://youtu.be/sZa26_esLBE)

  • Hi i just to want to know when we use object casting..

    sorry about this newbie question i ve already asked to my tutor but
    didn't get it...
    i just wonder what will happen if we cast object..
    i just can't imagin..coz im just bit slow on creative thinking...
    my currently writing code is like this..
    Integer nextCustID = new Integer("123456");
    Customer customer = new Customer(nextCustID, "Fred");
    customers.put("First", customer);
    customer = (Customer) customers.get("First");
    System.out.println(customer);i don't know about object casting...............................

    You don't cast objects. You just cast references - widening or narrowing their "scope" along the inheritance hierarchy.
    String s = new String("Hello");
    Object o = (Object) s; // Explicit cast not necessary, just for clarification
    String s = (String) o;While "hello" might appear as a String, then as an Object, then again as a String, it is always a String. Only the reference type to it changes.

  • Copying Info objects  - When should we use Reference and Template

    Hi,
    Can anyone guide me when should we choose Reference or Template while copying the Keyfigures / Charatertistis.
    Thanks,
    David

    Hi David,
       You can not see reference key figures. In updaterules.
    More info, Please see the below post:
    Re: InfoObject are not appearing in UpdateRules
    Hope it Helps
    Srini
    Message was edited by: Srini

  • Why or When should we use Execute Immediate in PLSQL??

    Hi Frnds,
    Long Ago i have received a interview question that ...
    How can U create a table in the PLSQL object(Function or procedure)?
    But the thing y should we use execute immediate?
    In which scenario we should we should use????????????
    Why or When should we use Execute Immediate in PLSQL????

    OR
    http://stackoverflow.com/questions/18375990/oracle-what-does-execute-immediate-means
    For DML you'd use it when running statements that you don't have available at compile time, e.g. if the column list is based on a selection from the user.
    In your case it's being used because DDL cannot be run as static SQL from within PL/SQL. Only certain query, DML and TCL commands are valid. Anything else has to be treated as dynamic.
    I'd say it's rare to need to use DDL from a PL/SQL block. TRUNCATE might be reasonable; if you find anything creating or dropping objects on the fly then that might be more of a concern as it can suggest a suboptimal data model.
    EXECUTE IMMEDIATE itself does not automatically commit; but if you execute DDL then that will behave the same as if you ran it outside PL/SQL, so it will commit in your case, yes.
    Incidentally, I'm not sure why your code is using an intermediate variable to hold the statement; that's useful if you want to display what it's going to run maybe, but you don't seem to be doing that. What you have could be done as:
    EXECUTE IMMEDIATE 'TRUNCATE TABLE BD_BIDS_EXT_DET';
    Thank you

  • When should a subclass have its own fields and when should it use its super

    When should a subclass have its own fields and when should it use its superclass' fields?
    Hi, thank you for reading this post!
    Let me use a specific example to ask my question.
    public class BankAccount {
         private double accountBalance;
         public double getBalance() {
              return this.accountBalance;
    public class SavingsAccount extends BankAccount {
         private double accountBalance;
         public double getBalance() {
              return this.accountBalance;
    }In the bank account example, both BankAccount and SavingsAccount will have a method getBalance(). Therefore, they
    both require a account balance field. My question is since getBalance() for both classes will perform the exact same
    operation, when should I omit declaring the getBalance() method and the accountBalance field in the subclass, and
    when should I include them?
    My own thought is when we never have to instantiate a superclass object (e.g. an abstract class), then we place
    common fields in the abstract superclass and have subclasses access these fields via protected getter/setters to
    access the superclass' fields. This is the principle of reuse.
    But when you do need to instantiate a superclass and the superclass does need to maintain its own fields, then
    I would need to duplicate the accountBalance field and getBalance() method in the subclass.
    Is my thinking correct or incorrect?
    Thank you in advance for your help!
    Eric
    Edited by: er**** on 22-Aug-2011 20:19

    er**** wrote:
    If SavingsAccount inherit BankAccount.getBalance()...getBalance() would return BankAccount's accountBalance. This is NOT the correct result we want.Actually, I think it's precisely what you want.
    We want getBalance() to return BankAccount's accountBalance when we use a BankAccount object, and SavingsAccount's accountBalance when we use a SavingsAccount object.I seriously doubt that. I think you're confusing a BankAccount with a Customer, who can have more than one account.
    In every system I've ever seen, a SavingsAccount IS-A BankAccount - that is to say, it's a genuine subtype. Now, it may well contain other fields ('interest'?) that a normal account wouldn't, but 'balance' ain't one of them.
    Winston

  • When should use ACCESS?

    Hi all,
    I have written a java program to load some data (text file) into ACCESS database. It is fine for testing. Once I put it into my real data (about 1.3 MB), it doesn't work. After I check with my tables, some data is missing. I really don't know why. I can't see any exception error messages.
    Then, I suspected that is the problem of ACCESS, therefore, I turned autoCommit into false, and commited it finally, but it still doesn't work. So, are there any techniques can help?
    Actually, can anybody give me some suggestions, how large the data should be stored in ACCESS. When should us give up ACCESS.

    I think it is better for me to answer my question, so
    that it is helpful fo other programmers who have
    encountered same problem.
    This problem doesn't come from wrong codes, but for
    reliability of ACCESS, at least I suspect. In my case,
    although I have only one mega data for loading, this
    data involved a lot of relationship (a lot of tables).
    Therefore, It is not sufficient to just mention how
    large you raw data is. If your raw data will generate
    multiple relationships, it will be another story.
    My solution is, setting autocommit to false, and comit
    it for each 10 objects(which involved several insert
    statements for several tables). It is functionable. I
    think that ACCESS is just for development and testing.
    But, I have a question, who know the max capacity of
    ACCESS in term of MB?
    Still don't know what you are talking about. The usage I saw for MS Access was for financial transactions for banking purposes. I know that it has also been used for medical records. And it has been used extensively for small retail.
    And to my mind that means it is not just "for developement and testing."
    And if you think Oracle and MS SQL Server can't end up with corrupted databases, then you might want to do some research into that. I know that they can. And there is certainly no reason to believe that other databases are perfect in that regard.
    Most of the cases that I am familar with where there are problems with corrupt data in MS Access it can be usually be traced to poor user practices. Such as hitting the power down button instead of using shutdown. And that would undoubtly cause problems with Oracle and MS SQL Server as well, but you don't see that as much because admins deal with servers and their training usually includes enough info so that they know not to do that.

  • When should I use static variable and when should not? Java essential

    When should I use static variable and when should not? Java essential

    Static => same value for all instances of the class.
    Non-static => each instance can have its own value.
    Which you need in which circumstances is completely up to you.

  • What is the necessity of the AC power cord (with Mac Book Air)? When should it be used with the power adapter?

    what is the necessity of the AC power cord (with the Mac book Air)? when should it be used?

    Gary, you wouldn't believe some of the questions people ask on this site.
    Why are both cords necessary?
    They are not.
    Other than the two reasons dominic23 sited are there any other reasons to use the AC power cord rather than the power adapter cord alone?
    No.

  • What is a Transient Variable and when should it be used

    Hello everyone,
    I just want to know the details regarding the transient variable and when should we use it. what is the significance of this variable?

    Transient variables are not written out when the class is serialized.
    http://java.sun.com/docs/books/tutorial/essential/io/providing.html

Maybe you are looking for

  • Can you bring your phone back from an accidental restore?

    I just got the iphone 4. I plugged it up to my itunes and it asked to restore from previous iphone or retore like a new phone. I picked from previous phone. Well it ended up clearing EVERYTHING off. All the stuff I had transfered. So my question is c

  • Running Boot Camp in Windows 7 with Bluetooth Wireless Keyboard and Wireless Magic Mouse

    NOTE: I was installing a fresh copy of Windows 7 Professional on a 27" iMac mid-2010 with a Processor Speed of 2.93 GHz, a Core i7 Processor Type,  a Quad Core Processor Configuration, 8GB RAM, and a ATI Radeon HD 5750 Graphics Card.  I run Snow Leop

  • Creative suite 4 "unattended" install

    Im trying to deploy cs4 silently, but with a progress bar so users can see when it is finished installing (unattended). I know you could do that in cs3, but apparently from what ive found they dont do that anymore in cs4. Unless they have another mod

  • Oracle 8.0.6 download

    Hi, Does somebody know where I can still download an Oracle 8.0.6 cpio file for hpux11? In the past I could find it in download.oracle.com, but now otn is not available anymore. Thanks, DD

  • APO Capacity Reservation Characteristic is not valid

    Hello We are trying to setup a scenario for capacity reservation for customers wherein we want to reserve capacity for certain customers. We did the following setup as mentioned in help http://help.sap.com/saphelp_scm70/helpdata/EN/46/19bf1f8716424fe