{"id":4385,"date":"2014-03-30T10:22:14","date_gmt":"2014-03-30T10:22:14","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/problem-about-downcasting-collection-of-common-programming-errors\/"},"modified":"2014-03-30T10:22:14","modified_gmt":"2014-03-30T10:22:14","slug":"problem-about-downcasting-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/03\/30\/problem-about-downcasting-collection-of-common-programming-errors\/","title":{"rendered":"problem about downcasting-Collection of common programming errors"},"content":{"rendered":"<ul>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/w7ipG.jpg?s=32&amp;g=1\" \/><br \/>\ndragonaid<br \/>\njava casting downcasting<br \/>\nThis question already has an answer here:Downcasting in Java8 answersCan anyone here please explain to me why I get a java.lang.ClassCastException when downcasting a Parent to a Child?public class Child extends Parent{ public static void main(String[] args){new Child().go(); } void go(){go2(new Parent(), new Child());go2((Child) new Parent(), new Child()); } void go2(Parent p1, Child c1){Child c2 = (Child)p1;Parent p2 = (Parent)c1; } } class Tree{}I have read reference variable casting and sear<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/yndwE.png?s=32&amp;g=1\" \/><br \/>\nMastergeek<br \/>\njava object casting double downcasting<br \/>\nSay I have this:Object obj = new Double(3.14);Is there a way to use obj like a Double without explicitly casting it to Double? For instance, if I wanted to use the .doubleValue() method of Double for calculations.<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/c66a72ac244823d60909cde37c7e58fd?s=32&amp;d=identicon&amp;r=PG&amp;f=1\" \/><br \/>\nAlienArrays<br \/>\njava inheritance object polymorphism downcasting<br \/>\nI was trying to do something likeclass O has a child EI declare the variable O xyz = new E();but then if I call xyz.method(), I can only call those in class O&#8217;s methods, not E&#8217;s, so I can downcast it byE xyz2 = (E) xyz;My question is- Can you do this without declaring a new variable? Something like:O xyz = new E(); xyz = (E) xyz; and now I can use xyz.method() to call E&#8217;s methods Is there a way to do this in java?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/4nf3j.jpg?s=32&amp;g=1\" \/><br \/>\nAlex Shesterov<br \/>\njava list inheritance casting downcasting<br \/>\nI&#8217;m having trouble casting a List of Fruit down to the Fruit subclass contained in the List. public class Response {private List&lt;Fruit&gt; mFruitList;public List&lt;Fruit&gt; getFruitList() {return mFruitList;} } public class Fruit { }public class Orange extends Fruit { }List&lt;Fruit&gt; oranges = response.getFruitList();How do I cast oranges so that it is a List of class Orange? Is this a bad design pattern? Basically I am getting a JSON Response from a server that is a List of Fruit. For<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/a3ee8200bdf6f4b6b1cd25579b26f421?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nSyed Zahid Ali<br \/>\njava object arraylist downcasting up-casting<br \/>\nI have a situation in which I am getting data from database, and I want to upcast it to ArrayList of objects and then downcast it to different custom ArrayList i.e. List&lt;User&gt;, List&lt;Groups&gt; etc.My question is up-casting to object and then down-casting to ArrayList, what will be the cost, and is it efficient or good practice.EDITEDInstead of getting data as List&lt;User&gt;, List&lt;Groups&gt; etc I want to get data as ArrayList&lt;objetcs&gt; once and then as per my need, I will dow<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/94e2dd813e278309b6281b4a4b7fdddd?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\ncuriousguy<br \/>\nc++ multiple-inheritance dynamic-cast downcasting virtual-inheritance<br \/>\nI tried creating a class that inherits from multiple classes as followed, getting a &#8220;diamond&#8221; (D inherits from B and C. B and C both inherits from A virtually): \u00a0 A\u00a0 \/ \\B \u00a0 C\u00a0 \\ \/\u00a0 DNow, I have a container with a linked list that holds pointers to the base class (A). When I tried doing explicit casting to a pointer (after typeid check) I got the following error: &#8220;cannot convert a pointer to base class &#8220;A&#8221; to pointer to derived class &#8220;D&#8221; &#8212; base class is virtual&#8221;<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/vul9z.jpg?s=32&amp;g=1\" \/><br \/>\nBirdman<br \/>\njava swing awt graphics2d downcasting<br \/>\nI&#8217;m trying to figure out why it is allowed to downcast a Graphics instance to a Graphics2D instance.It&#8217;s usually against the rules to downcast a reference type that isn&#8217;t inheriting the target type.In the graphic-oriented classes the hierarchy is like the following:Graphics is the superclass Graphics2D is the subclass of the superclass GraphicsWhen drawing something in Swing you override the paint() method &#8211; And if you&#8217;re in need of 2D-drawing you downcast the automatically supplied Graphics ins<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/6534d130fd71ef6ee245002878d3c2af?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nKlamann<br \/>\njava class generics downcasting<br \/>\nIn a generic method, I don&#8217;t seem to be able to access the generic type of the method at runtime (error: cannot select from a type variable).public &lt;A&gt; A get(Animal a) {Class ac = a.getClass();if(ac.isAssignableFrom(A.class)) { \/\/ &lt;- not working!return (A) a;} else {\/\/ error handling} }The reason why I do this is to be able to safely downcast stuff, like:Animal a = new Dog(); Dog d = get(a); \/\/ &lt;- OK Cat c = get(a) \/\/ &lt;- incompatible types, caught by else blockI&#8217;ve found a<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/c961ce2e2afe29ac71a816f3038d4418?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nSudheer<br \/>\njava casting type-conversion downcasting downcast<br \/>\npublic class InheritanceDemo {public static void main(String[] args) {ParentClass p = new ParentClass();ChildClass c = new ChildClass();\/\/Casting ChildClass to ParentClassParentClass pc = new ChildClass();pc.parentClassMethod(); \/\/Output: Parent Class Method (as expected)\/\/Again Casting Parent Class to ChildClass explictly\/\/Question 1 for this codeChildClass cp = (ChildClass) pc;cp.parentClassMethod(); \/\/Output: Parent Class Method (unexpected)ChildClass cc1 = (ChildClass) new ParentClass();cc1.<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/23de335ea2208b179ece18bec0b2597f?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nBuhake Sindi<br \/>\njava downcasting<br \/>\nRun time exception&#8211; java.lang.ClassCastingException&#8230;Integer intArr[] = new Integer[arrList.size()]; ArrayList &lt;Integer&gt; arrList =new ArrayList(); intArr=(Integer[])arrList.toArray(); \/\/ returns Object class which is downcaste to Integer;I understand down-casting is not safe but why is this happening? I also tried to converting ArrayList to String to Integer to int, but I get the same error.<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/e8eb1671ae3bf4a7536c1aa2c3276779?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nekkis<br \/>\nc# entity-framework asp.net-mvc-3 casting downcasting<br \/>\nI have a project where I&#8217;ve defined in EF an Employer as a derived class of User. In my process I create a user without knowing whether it will eventually be an employer (or other kinds of users) and later I need to convert it. At first I tried (Intellisense indicated an explicit conversion exists):Employer e = (Employer) GetUser();but at runtime I got:Unable to cast object of type &#8216;System.Data.Entity.DynamicProxies.User_7B&#8230;0D&#8217; to type &#8216;Employer&#8217;.so I tried to write a converter:public partia<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/77302a6c0989999e15aebc7968310acb?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nZiv<br \/>\nc++ casting private downcasting<br \/>\nA tweak on this question that I&#8217;ve run into. Consider:class A {};class B : private A {static void foo(); };void B::foo(){B* bPtr1 = new B;A* aPtr1 = dynamic_cast&lt;A*&gt;(bPtr1); \/\/ gives pointerB* bPtr2 = dynamic_cast&lt;B*&gt;(aPtr1); \/\/ gives NULL }Since aPtr1 is, in fact, of type B*, and since we&#8217;ve got full access to B and its inheritance from A, I&#8217;d expected both casts to work. But they don&#8217;t; why? Is there another way to achieve this cast?Note that:If foo() were not a member of B, both c<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/2dd35668d8f2c8931d75793fc3a52cf6?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nAbruzzo Forte e Gentile<br \/>\nc++ casting downcasting<br \/>\nI am reviewing C++ casts operator and I have the following doubt:for polymorphic classes I I should use polymorphic_cast I should never use of static_cast since down-casting might carry to undefined behavior. The code compiles this case anyway.Now suppose that I have the following situtationclass CBase{}; class CDerived : public CBase{};int main( int argc, char** argv ){CBase* p = new CDerived();\/\/.. do somethingCDerived*pd = static_cast&lt;CDerived*&gt;( p ); }Since there is no polymorphism in<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/b3ccac435e2fd4eb9be62da7830d887c?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\njedwards<br \/>\nc++ stl shared-ptr downcasting<br \/>\nConsider the following outline:class Base { \/* &#8230; *\/ };class Derived : public Base { public:void AdditionalFunctionality(int i){ \/* &#8230; *\/ } };typedef std::shared_ptr&lt;Base&gt; pBase; typedef std::shared_ptr&lt;Derived&gt; pDerived;int main(void) {std::vector&lt;pBase&gt; v;v.push_back(pBase(new Derived()));pDerived p1( std::dynamic_pointer_cast&lt;Derived&gt;(v[0]) ); \/* Copy *\/pDerived p2 = std::dynamic_pointer_cast&lt;Derived&gt;(v[0]); \/* Assignment *\/p1-&gt;AdditionalFunctionality(1<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/3189f1e006358ec6c65481b9605cd0e3?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nLightness Races in Orbit<br \/>\nc++ virtual-inheritance downcasting static-cast<br \/>\nConsider the following code:struct Base {}; struct Derived : public virtual Base {};void f() {Base* b = new Derived;Derived* d = static_cast&lt;Derived*&gt;(b); }This is prohibited by the standard ([n3290: 5.2.9\/2]) so the code does not compile, because Derived virtually inherits from Base. Removing the virtual from the inheritance makes the code valid.What&#8217;s the technical reason for this rule to exist?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/6a73ff6b01017a13d590122dfb7a3f2c?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nCodeKingPlusPlus<br \/>\nc++ inheritance casting downcasting downcast<br \/>\nI have my base class as follows: class point \/\/concrete class {&#8230; \/\/implementation }class subpoint : public point \/\/concrete class { &#8230; \/\/implementation }How do I cast from a point object to a subpoint object? I have tried all three of the following:point a; subpoint* b = dynamic_cast&lt;subpoint*&gt;(&amp;a); subpoint* b = (subpoint*)a; subpoint b = (subpoint)a;What is wrong with these casts?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/03682fb0f97c46f552ec83a59f5ee8b7?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nhuy<br \/>\nc++ downcasting<br \/>\nI have a simple hierarchy tree structure with a base class Node representing a node. A node could be of another specific type (subclassing).class Node {vector&lt;Node*&gt; childs;\/\/ simple node manipulation methodsconst vector&lt;Node*&gt;&amp; getChildren() { return childs; } }and I have a couple of subclasses of Node:class FacultyNode : public Node; &#8230; class DepartmentNode : public Node; &#8230;Say I know that all children of a faculty node is of DepartmentNode type, to save the developer&#8217;s work<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/96c012979732c0bd124f5157e5e4bd55?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nnahpr<br \/>\nc++ void-pointers downcasting<br \/>\nSo I go this:class A;class B : public A;class C : public B;vector&lt;A*&gt; *vecA;vector&lt;C*&gt; *vecC;And I want to cast a vectC into a vecA.vector&lt;A*&gt; *_newA = static_cast&lt; vector&lt;A*&gt;* &gt;(vecC); \/\/gives an errorSo I used void pointer as a buffer and the cast:void *buffer = vecC;vector&lt;A*&gt; *_newA = static_cast&lt; vector&lt;A*&gt;* &gt;(buffer); \/\/worksIs this valid? Is there another way to do it?<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/07123541fba3343f9ddb5876595b99a7?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nAlex<br \/>\nc++ polymorphism downcasting up-casting<br \/>\nI have the following classes:class State {protected:Vec3D accel;Vec3D gyro;Vec3D gps;float reward;public:boost::ptr_vector&lt;Action&gt; actions;&#8230;virtual bool isTerm(); }class guState : public State { float gps_stand_thres;float gps_down_thres;public:guState(Agent &amp;A,ACTION_MODE &amp;m);bool isTerm(); };There are other classes which all inherit from State. Their differences solely lie on how they evaluate isTerm() which depends on behavior. I would rather not use virtual functions bur ove<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/c5ee00b0b4173e1957a3483697bedcea?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nSumit Das<br \/>\nc++ inheritance downcasting<br \/>\nHere&#8217;s a piece of code I had written to see the behaviour during downcasting.#include &lt;iostream&gt; using namespace std;class base { public :void function(){cout &lt;&lt; &#8220;\\nInside class Base&#8221;;} };class derived : public base { public :void function(){cout &lt;&lt; &#8220;\\nInside class Derived.&#8221;;} };int main() {base * b1 = new base();base * b2 = new derived();derived * b3 = (derived*)b1 ;b1 -&gt; function();b2 -&gt; function();b3 -&gt; function(); \/\/ print statement 3static_cast&lt;derived*&gt;(b2)<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/1340e3bb4dc844b1abf246ef14afb6e3?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nBogdan Vasilescu<br \/>\nc pointers type-conversion downcasting<br \/>\nPointer Downcastint* ptrInt;char * ptrChar;void* ptrVoid;unsigned char indx;int sample = 0x12345678;ptrInt = &amp;sample;ptrVoid = (void *)(ptrInt);ptrChar = (char *)(ptrVoid);\/*manipulating ptrChar *\/for (indx = 0; indx &lt; 4; indx++){printf (&#8220;\\n Value: %x \\t Address: %p&#8221;, *(ptrChar + indx), ( ptrChar + indx)); }Output:Value: 00000078 Address: 0022FF74Value: 00000056 Address: 0022FF75Value: 00000034 Address: 0022FF76Value: 00000012 Address: 0022FF77Question: Why<\/li>\n<li><img decoding=\"async\" src=\"http:\/\/www.gravatar.com\/avatar\/bba4247e6f4aa21a0f4037fb98661760?s=32&amp;d=identicon&amp;r=PG\" \/><br \/>\nFrion3L<br \/>\nc++ inheritance downcasting<br \/>\nI have a doubt about downcasting an object in C++.Here it comes an example:class A { } class B : public A { public:void SetVal(int i) { _v = i; }private:int _v; }A* a = new A(); B* b = dynamic_cast&lt;B*&gt;(a); b-&gt;SetVal(2);What would it happen with this example? We are modifying a base clase like if it is a child one&#8230; how does it work related with the memory? With this cast&#8230; Is it like creating an instance of B and copying the values of A?Thanks<\/li>\n<\/ul>\n<p>Web site is in building<\/p>\n","protected":false},"excerpt":{"rendered":"<p>dragonaid java casting downcasting This question already has an answer here:Downcasting in Java8 answersCan anyone here please explain to me why I get a java.lang.ClassCastException when downcasting a Parent to a Child?public class Child extends Parent{ public static void main(String[] args){new Child().go(); } void go(){go2(new Parent(), new Child());go2((Child) new Parent(), new Child()); } void go2(Parent [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-4385","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4385","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=4385"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/4385\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=4385"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=4385"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=4385"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}