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
Solved

containers and casting

Posted on 2004-10-09
22
218 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

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

 
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

Suggested Solutions

Title # Comments Views Activity
java stored proc example 9 44
ejb wildfly example 2 25
jsp login check 12 42
What browser will run Java? 7 62
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

839 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