Solved

containers and casting

Posted on 2004-10-09
22
216 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
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
 
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
allswap challenge 6 80
Starting to learn JAVA, 7 59
Free Alternative to JIRA 4 91
Java Options in Zimbra Server 2 46
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

867 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

21 Experts available now in Live!

Get 1:1 Help Now