Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

containers and casting

Posted on 2004-10-09
22
Medium Priority
?
223 Views
Last Modified: 2010-03-31
If I put a Car object in a generic Object container

ie.
Car myCar = new Car();
Object carObj = myCar;

can I then convert the Object (carObj) back to a Car object?

I tried casting carObj to a Car, but it's not allowed by java, so it says
0
Comment
Question by:adam8
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 11
  • 10
22 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 200 total points
ID: 12265543
Car original = (Car)carObj;
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12265550
(Assuming 'carObj' is of type Object and holds a valid Car reference):

      Object carObj = new Car();
      Car original = (Car)carObj;
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 12265569


Car carObject=new Car();

FindInstance(o);

void FindInstance(Object o)
{
    if(o instanceof Car)
    {
               Car car=(Car)o;
               System.err.println("Car Instance is retreived back from Object");
    }
     else
   {
                       System.err.println("I don't know abt this instace");
    }
}
 
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:adam8
ID: 12265855
hmmm, that's strange, i did exactly that before and it told me they were inconvertible types.. Works now for some reason though
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12265858
It can't have been that that you did before ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12265861
8-)
0
 
LVL 1

Author Comment

by:adam8
ID: 12265865
actually, i'll try it yet again and give you my exact code, if you can be bothered
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12265870
Fire away!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12265877
(but you'll have to be quick- i'm going at any moment!)
0
 
LVL 1

Author Comment

by:adam8
ID: 12265897
sorry. I was trying to type it all again, Um, will this work with an array of objects, becaues that could be why it wasn't working. You can look at the code next time you have spare time if you have to go.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12265909
If you have an array to cast, you can't apply the cast to that in the exact same way as you apply it to the above.
0
 
LVL 1

Author Comment

by:adam8
ID: 12265912
public class Test
{
      public static void main(String[] args)
      {
            Dog[] theDog = new Dog[1];
            theDog[0] = new Dog("Woofer");

            theDog = (Dog[])(resizeArray(theDog, 1));
      }

      private static Object[] resizeArray(Object[] inArray, int extendBy)
      {
            Object[] result = new Object[inArray.length + extendBy];

            for (int i = 0; i < inArray.length; i++)
            {
                  result[i] = inArray[i];
            }

            return result;
      }
}

class Dog
{
      private String name;
      
      public Dog(String nam, int years)
      {
            name = nam;
      }

      public String getName()
      {
            return name;
      }
}
0
 
LVL 1

Author Comment

by:adam8
ID: 12265916
Ah, sorry, that won't compile, this is the code that i'm having trouble with.
0
 
LVL 1

Author Comment

by:adam8
ID: 12265920
public class Test
{
      public static void main(String[] args)
      {
            Dog[] theDog = new Dog[1];
            theDog[0] = new Dog("Woofer");

            theDog = (Dog[])(resizeArray(theDog, 1));
      }

      private static Object[] resizeArray(Object[] inArray, int extendBy)
      {
            Object[] result = new Object[inArray.length + extendBy];

            for (int i = 0; i < inArray.length; i++)
            {
                  result[i] = inArray[i];
            }

            return result;
      }
}

class Dog
{
      private String name;

      public Dog(String nam)
      {
            name = nam;
      }

      public String getName()
      {
            return name;
      }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12265963
Doesn't work in the same way. You create an array of type Object[]. While you can cast each element in your case individually, you can't cast the type of the array itself. You can do what you want thus (using System.arraycopy for efficiency):

     private static Object[] resizeArray(Object[] inArray, int extendBy)
     {
          Object _result = java.lang.reflect.Array.newInstance(inArray[0].getClass(), inArray.length + extendBy);
          Object[] result = (Object[])_result;
          System.arraycopy(inArray, 0, result, 0, inArray.length);
          return result;
     }
0
 
LVL 1

Author Comment

by:adam8
ID: 12265986
ok, one last question, i don't understand the _ character in _result. Does it have any special meaning.

Thanks very much for your help also.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12265994
Just to distinguish it from the other result variable. The whole thing could be written:

     private static Object[] resizeArray(Object[] inArray, int extendBy)
     {
          Object[] result = (Object[])java.lang.reflect.Array.newInstance(inArray[0].getClass(), inArray.length + extendBy);
          System.arraycopy(inArray, 0, result, 0, inArray.length);
          return result;
     }


0
 
LVL 1

Author Comment

by:adam8
ID: 12266018
thanks heaps.
0
 
LVL 1

Author Comment

by:adam8
ID: 12266047
act, sorry, one more problem, unfortunately all my arrays start at 0 length, and the inArray[0].getClass() throws errors since there aren't any elements, I don't suppose there is a way around this, because initially, there are no elements there to check what class type they are.

So for example Dog[] theDog = new Dog[0];

contains no elements until an element is added, hence the array has to be extended, if it can't be done I will just make the class specific resizing code where needed, instead of a generic code all the classes use.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12266074
>>I don't suppose there is a way around this

There is - override the method and pass the class:

     private static Object[] resizeArray(Class inArrayType, int extendBy)
     {
         // else
     }





0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12267155
>>There is - override the method and pass the class:

That should have said:

There is - overload the method and pass the class:
0
 
LVL 1

Author Comment

by:adam8
ID: 12268868
ok, thanks
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to implement Singleton Design Pattern in Java.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

721 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question