Solved

containers and casting

Posted on 2004-10-09
22
215 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
  • 11
  • 10
22 Comments
 
LVL 86

Accepted Solution

by:
CEHJ earned 50 total points
Comment Utility
Car original = (Car)carObj;
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
(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
Comment Utility


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
 
LVL 1

Author Comment

by:adam8
Comment Utility
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
Comment Utility
It can't have been that that you did before ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
8-)
0
 
LVL 1

Author Comment

by:adam8
Comment Utility
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
Comment Utility
Fire away!
0
 
LVL 86

Expert Comment

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

Author Comment

by:adam8
Comment Utility
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
Comment Utility
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 1

Author Comment

by:adam8
Comment Utility
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
Comment Utility
Ah, sorry, that won't compile, this is the code that i'm having trouble with.
0
 
LVL 1

Author Comment

by:adam8
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
thanks heaps.
0
 
LVL 1

Author Comment

by:adam8
Comment Utility
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
Comment Utility
>>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
Comment Utility
>>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
Comment Utility
ok, thanks
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

771 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

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now