Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

containers and casting

Posted on 2004-10-09
22
Medium Priority
?
225 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 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
Independent Software Vendors: 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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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

879 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