Search Results

Search found 763 results on 31 pages for 'casting'.

Page 4/31 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • SQL:Casting a String to IDS with IN clause

    - by Shyju
    DECLARE @STR_IDS VARCHAR(15) SET @STR_IDS='7,15,18' UPDATE TBL_USERS WHERE ID IN @STR_IDS I know the update statement would not work as the ID is of type INT and i am replacing a varachar value there .How can i change the query so that it will be executed like this in effect ? UPDATE TBL_USERS WHERE ID IN (7,15,18) Thanks in advace

    Read the article

  • Why does Java ArrayList use per-element casting instead of per-array casting?

    - by user1111929
    What happens inside Java's ArrayList<T> (and probably many other classes) is that there is an internal Object[] array = new Object[n];, to which T Objects are written. Whenever an element is read from it, a cast return (T) array[i]; is done. So, a cast on every single read. I wonder why this is done. To me, it seems like they're just doing unnecessary casts. Wouldn't it be more logical and also slightly faster to just create a T[] array = (T[]) new Object[n]; and then just return array[i]; without cast? This is only one cast per array creation, which is usually far less than the number of reads. Why is their method to be preferred? I fail to see why my idea isn't strictly better?

    Read the article

  • casting char* to char**

    - by blue_whale
    I am having a tough time understanding the following piece of code: int stride = 512; int max_len = 1024 * stride; char *addr = (char *)malloc(max_len); for (int i=stride; i<max_len; i += stride) *(char **)&addr[i-stride] = (char*)&addr[i]; *(char **)&addr[i-stride] = (char*)&addr[0]; Looking at the code it seems this is trying to create some kind of circular link list. But I have no clue what those casts are actually doing.

    Read the article

  • Type casting int into double C++

    - by user1705380
    I am new to programming and this might be an obvious question, though i cannot for life of me figure out why my program is not returning as a double. I am suppose to write a stocks program that takes in shares of stock, whole dollar portion of price and the fraction portion. And the fraction portion is to be inputted as two int values, and include a function definition with 3 int values.The function returns the price as a double. #include <iostream> using namespace std; int price(int, int, int); int main() { int dollars, numerator, denominator, price1, shares; char ans; do { cout<<"Enter the stock price and the number of shares.\n"; cout<<"Enter the price and integers: Dollars, numerator, denominator\n"; cin>>dollars>>numerator>>denominator; cout<<"Enter the number of shares held\n"; cin>>shares; cout<<shares; price1 = price(dollars,numerator,denominator); cout<<" shares of stock with market price of "; cout<< dollars << " " << numerator<<'/'<<denominator<<endl; cout<<"have a value of " << shares * price1<<endl; cout<<"Enter either Y/y to continue"; cin>>ans; }while (ans == 'Y' || ans == 'y'); system("pause"); return 0; } int price(int dollars, int numerator, int denominator) { return dollars + numerator/static_cast<double>(denominator); }

    Read the article

  • Casting an object which could be null

    - by DeeMac
    DateTime? testDate = (DateTime?)arrayOfObjects[dateObject]; Does that code look ok? I attempted to use the as operator but I got the 'non-nullable' error. What I'm trying to say is that the object I'm choosing from the array is either DateTime or a null DateTime but either can be assigned to testDate. Doesn't feel right doing it this way, I think I'm missing something obvious. EDIT: I suppose it's the same as the way I could've adapted the as in the following way: DateTime? testDate = arrayOfObjects[dateObject] as DateTime?; Is either line of code the best way of handling potential nulls?

    Read the article

  • What does this C++ construct do?

    - by cambr
    Somewhere in lines of code, I came across this construct... //void* v = void* value from an iterator int i = (int)(long(v)) What possible purpose can this contruct serve? Why not simply use int(v) instead? Why the cast to long first?

    Read the article

  • C#/.NET Little Pitfalls: The Dangers of Casting Boxed Values

    - by James Michael Hare
    Starting a new series to parallel the Little Wonders series.  In this series, I will examine some of the small pitfalls that can occasionally trip up developers. Introduction: Of Casts and Conversions What happens when we try to assign from an int and a double and vice-versa? 1: double pi = 3.14; 2: int theAnswer = 42; 3:  4: // implicit widening conversion, compiles! 5: double doubleAnswer = theAnswer; 6:  7: // implicit narrowing conversion, compiler error! 8: int intPi = pi; As you can see from the comments above, a conversion from a value type where there is no potential data loss is can be done with an implicit conversion.  However, when converting from one value type to another may result in a loss of data, you must make the conversion explicit so the compiler knows you accept this risk.  That is why the conversion from double to int will not compile with an implicit conversion, we can make the conversion explicit by adding a cast: 1: // explicit narrowing conversion using a cast, compiler 2: // succeeds, but results may have data loss: 3: int intPi = (int)pi; So for value types, the conversions (implicit and explicit) both convert the original value to a new value of the given type.  With widening and narrowing references, however, this is not the case.  Converting reference types is a bit different from converting value types.  First of all when you perform a widening or narrowing you don’t really convert the instance of the object, you just convert the reference itself to the wider or narrower reference type, but both the original and new reference type both refer back to the same object. Secondly, widening and narrowing for reference types refers the going down and up the class hierarchy instead of referring to precision as in value types.  That is, a narrowing conversion for a reference type means you are going down the class hierarchy (for example from Shape to Square) whereas a widening conversion means you are going up the class hierarchy (from Square to Shape).  1: var square = new Square(); 2:  3: // implicitly convers because all squares are shapes 4: // (that is, all subclasses can be referenced by a superclass reference) 5: Shape myShape = square; 6:  7: // implicit conversion not possible, not all shapes are squares! 8: // (that is, not all superclasses can be referenced by a subclass reference) 9: Square mySquare = (Square) myShape; So we had to cast the Shape back to Square because at that point the compiler has no way of knowing until runtime whether the Shape in question is truly a Square.  But, because the compiler knows that it’s possible for a Shape to be a Square, it will compile.  However, if the object referenced by myShape is not truly a Square at runtime, you will get an invalid cast exception. Of course, there are other forms of conversions as well such as user-specified conversions and helper class conversions which are beyond the scope of this post.  The main thing we want to focus on is this seemingly innocuous casting method of widening and narrowing conversions that we come to depend on every day and, in some cases, can bite us if we don’t fully understand what is going on!  The Pitfall: Conversions on Boxed Value Types Can Fail What if you saw the following code and – knowing nothing else – you were asked if it was legal or not, what would you think: 1: // assuming x is defined above this and this 2: // assignment is syntactically legal. 3: x = 3.14; 4:  5: // convert 3.14 to int. 6: int truncated = (int)x; You may think that since x is obviously a double (can’t be a float) because 3.14 is a double literal, but this is inaccurate.  Our x could also be dynamic and this would work as well, or there could be user-defined conversions in play.  But there is another, even simpler option that can often bite us: what if x is object? 1: object x; 2:  3: x = 3.14; 4:  5: int truncated = (int) x; On the surface, this seems fine.  We have a double and we place it into an object which can be done implicitly through boxing (no cast) because all types inherit from object.  Then we cast it to int.  This theoretically should be possible because we know we can explicitly convert a double to an int through a conversion process which involves truncation. But here’s the pitfall: when casting an object to another type, we are casting a reference type, not a value type!  This means that it will attempt to see at runtime if the value boxed and referred to by x is of type int or derived from type int.  Since it obviously isn’t (it’s a double after all) we get an invalid cast exception! Now, you may say this looks awfully contrived, but in truth we can run into this a lot if we’re not careful.  Consider using an IDataReader to read from a database, and then attempting to select a result row of a particular column type: 1: using (var connection = new SqlConnection("some connection string")) 2: using (var command = new SqlCommand("select * from employee", connection)) 3: using (var reader = command.ExecuteReader()) 4: { 5: while (reader.Read()) 6: { 7: // if the salary is not an int32 in the SQL database, this is an error! 8: // doesn't matter if short, long, double, float, reader [] returns object! 9: total += (int) reader["annual_salary"]; 10: } 11: } Notice that since the reader indexer returns object, if we attempt to convert using a cast to a type, we have to make darn sure we use the true, actual type or this will fail!  If the SQL database column is a double, float, short, etc this will fail at runtime with an invalid cast exception because it attempts to convert the object reference! So, how do you get around this?  There are two ways, you could first cast the object to its actual type (double), and then do a narrowing cast to on the value to int.  Or you could use a helper class like Convert which analyzes the actual run-time type and will perform a conversion as long as the type implements IConvertible. 1: object x; 2:  3: x = 3.14; 4:  5: // if you want to cast, must cast out of object to double, then 6: // cast convert. 7: int truncated = (int)(double) x; 8:  9: // or you can call a helper class like Convert which examines runtime 10: // type of the value being converted 11: int anotherTruncated = Convert.ToInt32(x); Summary You should always be careful when performing a conversion cast from values boxed in object that you are actually casting to the true type (or a sub-type). Since casting from object is a widening of the reference, be careful that you either know the exact, explicit type you expect to be held in the object, or instead avoid the cast and use a helper class to perform a safe conversion to the type you desire. Technorati Tags: C#,.NET,Pitfalls,Little Pitfalls,BlackRabbitCoder

    Read the article

  • Google I/O 2010 - Casting a wide net for all Android devices

    Google I/O 2010 - Casting a wide net for all Android devices Google I/O 2010 - Casting a wide net: How to target all Android devices Android 201 Justin Mattson One of Android's strengths is its flexibility to run on a wide variety of devices. In this session, we will explore the facilities the Android resource system provides to developers to make supporting many devices from one application binary easier, as well as common pitfalls. In addition to hardware heterogeneity, more than one version of Android may exist in the wild at any given time. We will go over strategies for providing cross-version compatibility. For all I/O 2010 sessions, please go to code.google.com From: GoogleDevelopers Views: 4 0 ratings Time: 01:02:15 More in Science & Technology

    Read the article

  • Writing the correct value in the depth buffer when using ray-casting

    - by hidayat
    I am doing a ray-casting in a 3d texture until I hit a correct value. I am doing the ray-casting in a cube and the cube corners are already in world coordinates so I don't have to multiply the vertices with the modelviewmatrix to get the correct position. Vertex shader world_coordinate_ = gl_Vertex; Fragment shader vec3 direction = (world_coordinate_.xyz - cameraPosition_); direction = normalize(direction); for (float k = 0.0; k < steps; k += 1.0) { .... pos += direction*delta_step; float thisLum = texture3D(texture3_, pos).r; if(thisLum > surface_) ... } Everything works as expected, what I now want is to sample the correct value to the depth buffer. The value that is now written to the depth buffer is the cube coordinate. But I want the value of pos in the 3d texture to be written. So lets say the cube is placed 10 away from origin in -z and the size is 10*10*10. My solution that does not work correctly is this: pos *= 10; pos.z += 10; pos.z *= -1; vec4 depth_vec = gl_ProjectionMatrix * vec4(pos.xyz, 1.0); float depth = ((depth_vec.z / depth_vec.w) + 1.0) * 0.5; gl_FragDepth = depth;

    Read the article

  • Nonstatic conversion functions; Casting different types, e.g. DirectX vector to OpenGL vector

    - by Markus
    I am currently working on a game "engine" that needs to move values between a 3D engine, a physics engine and a scripting language. Since I need to apply vectors from the physics engine to 3D objects very often and want to be able to control both the 3D, as well as the physics objects through the scripting system, I need a mechanism to convert a vector of one type (e.g. vector3d<float>) to a vector of the other type (e.g. btVector3). Unfortunately I can make no assumptions on how the classes/structs are laid out, so a simple reinterpret_cast probably won't do. So the question is: Is there some sort of 'static'/non-member casting method to achieve basically this: vector3d<float> operator vector3d<float>(btVector3 vector) { // convert and return } btVector3 operator btVector3(vector3d<float> vector) { // convert and return } Right now this won't compile since casting operators need to be member methods. (error C2801: 'operator foo' must be a non-static member)

    Read the article

  • Why is casting and comparing in PHP faster than is_*?

    - by tstenner
    While optimizing a function in PHP, I changed if(is_array($obj)) foreach($obj as $key=$value { [snip] } else if(is_object($obj)) foreach($obj as $key=$value { [snip] } to if($obj == (array) $obj) foreach($obj as $key=$value { [snip] } else if($obj == (obj) $obj) foreach($obj as $key=$value { [snip] } After learning about ===, I changed that to if($obj === (array) $obj) foreach($obj as $key=$value { [snip] } else if($obj === (obj) $obj) foreach($obj as $key=$value { [snip] } Changing each test from is_* to casting resulted in a major speedup (30%). I understand that === is faster than == as no coercion has to be done, but why is casting the variable so much faster than calling any of the is_*-functions?

    Read the article

  • How can I draw an arrow at the edge of the screen pointing to an object that is off screen?

    - by Adam Henderson
    I am wishing to do what is described in this topic: http://www.allegro.cc/forums/print-thread/283220 I have attempted a variety of the methods mentioned here. First I tried to use the method described by Carrus85: Just take the ratio of the two triangle hypontenuses (doesn't matter which triagle you use for the other, I suggest point 1 and point 2 as the distance you calculate). This will give you the aspect ratio percentage of the triangle in the corner from the larger triangle. Then you simply multiply deltax by that value to get the x-coordinate offset, and deltay by that value to get the y-coordinate offset. But I could not find a way to calculate how far the object is away from the edge of the screen. I then tried using ray casting (which I have never done before) suggested by 23yrold3yrold: Fire a ray from the center of the screen to the offscreen object. Calculate where on the rectangle the ray intersects. There's your coordinates. I first calculated the hypotenuse of the triangle formed by the difference in x and y positions of the two points. I used this to create a unit vector along that line. I looped through that vector until either the x coordinate or the y coordinate was off the screen. The two current x and y values then form the x and y of the arrow. Here is the code for my ray casting method (written in C++ and Allegro 5) void renderArrows(Object* i) { float x1 = i->getX() + (i->getWidth() / 2); float y1 = i->getY() + (i->getHeight() / 2); float x2 = screenCentreX; float y2 = ScreenCentreY; float dx = x2 - x1; float dy = y2 - y1; float hypotSquared = (dx * dx) + (dy * dy); float hypot = sqrt(hypotSquared); float unitX = dx / hypot; float unitY = dy / hypot; float rayX = x2 - view->getViewportX(); float rayY = y2 - view->getViewportY(); float arrowX = 0; float arrowY = 0; bool posFound = false; while(posFound == false) { rayX += unitX; rayY += unitY; if(rayX <= 0 || rayX >= screenWidth || rayY <= 0 || rayY >= screenHeight) { arrowX = rayX; arrowY = rayY; posFound = true; } } al_draw_bitmap(sprite, arrowX - spriteWidth, arrowY - spriteHeight, 0); } This was relatively successful. Arrows are displayed in the bottom right section of the screen when objects are located above and left of the screen as if the locations of the where the arrows are drawn have been rotated 180 degrees around the center of the screen. I assumed this was due to the fact that when I was calculating the hypotenuse of the triangle, it would always be positive regardless of whether or not the difference in x or difference in y is negative. Thinking about it, ray casting does not seem like a good way of solving the problem (due to the fact that it involves using sqrt() and a large for loop). Any help finding a suitable solution would be greatly appreciated, Thanks Adam

    Read the article

  • Computation overhead in C# - Using getters/setters vs. modifying arrays directly and casting speeds

    - by Jeffrey Kern
    I was going to write a long-winded post, but I'll boil it down here: I'm trying to emulate the graphical old-school style of the NES via XNA. However, my FPS is SLOW, trying to modify 65K pixels per frame. If I just loop through all 65K pixels and set them to some arbitrary color, I get 64FPS. The code I made to look-up what colors should be placed where, I get 1FPS. I think it is because of my object-orented code. Right now, I have things divided into about six classes, with getters/setters. I'm guessing that I'm at least calling 360K getters per frame, which I think is a lot of overhead. Each class contains either/and-or 1D or 2D arrays containing custom enumerations, int, Color, or Vector2D, bytes. What if I combined all of the classes into just one, and accessed the contents of each array directly? The code would look a mess, and ditch the concepts of object-oriented coding, but the speed might be much faster. I'm also not concerned about access violations, as any attempts to get/set the data in the arrays will done in blocks. E.g., all writing to arrays will take place before any data is accessed from them. As for casting, I stated that I'm using custom enumerations, int, Color, and Vector2D, bytes. Which data types are fastest to use and access in the .net Framework, XNA, XBox, C#? I think that constant casting might be a cause of slowdown here. Also, instead of using math to figure out which indexes data should be placed in, I've used precomputed lookup tables so I don't have to use constant multiplication, addition, subtraction, division per frame. :)

    Read the article

  • Should I add try/catch around when casting on an attribute of JSP implicit object?

    - by Michael Mao
    Hi all: Basically what I mean is like this: List<String[]> routes = (List<String[]>)application.getAttribute("routes"); For the above code, it tries to get an attribute named "routes" from the JSP implicit object - application. But as everyone knows, after this line of code, routes may very well contains a null - which means this application hasn't got an attribute named "routes". Is this "casting on null" good programming practice in Java or not? Basically I try to avoid exceptions such as java.io.InvalidCastException I reckon things like this are more as "heritage" of Java 1.4 when generic types were not introduced to this language. So I guess everything stored in application attributes as Objects (Similar to traditional ArrayList). And when you do "downcast", there might be invalid casts. What would you do in this case? Update: Just found that although in the implicit object application I did store a List of String arrays, when I do this : List<double[]> routes = (List<double[]>)application.getAttribute("routes"); It doesn't produce any error... And I felt not comfortable already... And even with this code: out.print(routes.get(0)); It does print out something strange : [Ljava.lang.String;@18b352f Am I printing a "pointer to String"? I can finally get an exception like this: out.print(routes.get(0)[1]); with error : java.lang.ClassCastException: [Ljava.lang.String; Because it was me to add the application attribute, I know which type should it be cast to. I feel this is not "good enough", what if I forget the exact type? I know there are still some cases where this sort of thing would happen, such as in JSP/Servlet when you do casting on session attributes. Is there a better way to do this? Before you say:"OMG, why you don't use Servlets???", I should justify my reason as this: - because my uni sucks, its server can only work with Servlets generated by JSP, and I don't really want to learn how to fix issues like that. look at my previous question on this , and this is uni homework, so I've got no other choice, forget all about war, WEB-INF,etc, but "code everything directly into JSP" - because the professors do that too. :)

    Read the article

  • Is dynamic casting Entities A good design?

    - by Milo
    For my game, Everything inherits from Entity, then other things like Player, PhysicsObject, etc, inherit from Entity. The physics engine sends collision callbacks which has an Entity* to the B that A collided on. Then, lets say A is a Bullet, A tries to cast the entity as a player, if it succeeds, it reduces the player's health. Is this a good design? The problem I have with a message system is that I'd need messages for everything, like: entity.sendMessage(SET_PLAYER_HEALTH,16); So that's why I think casting is cleaner.

    Read the article

  • Dynamic Code for type casting Generic Types 'generically' in C#

    - by Rick Strahl
    C# is a strongly typed language and while that's a fundamental feature of the language there are more and more situations where dynamic types make a lot of sense. I've written quite a bit about how I use dynamic for creating new type extensions: Dynamic Types and DynamicObject References in C# Creating a dynamic, extensible C# Expando Object Creating a dynamic DataReader for dynamic Property Access Today I want to point out an example of a much simpler usage for dynamic that I use occasionally to get around potential static typing issues in C# code especially those concerning generic types. TypeCasting Generics Generic types have been around since .NET 2.0 I've run into a number of situations in the past - especially with generic types that don't implement specific interfaces that can be cast to - where I've been unable to properly cast an object when it's passed to a method or assigned to a property. Granted often this can be a sign of bad design, but in at least some situations the code that needs to be integrated is not under my control so I have to make due with what's available or the parent object is too complex or intermingled to be easily refactored to a new usage scenario. Here's an example that I ran into in my own RazorHosting library - so I have really no excuse, but I also don't see another clean way around it in this case. A Generic Example Imagine I've implemented a generic type like this: public class RazorEngine<TBaseTemplateType> where TBaseTemplateType : RazorTemplateBase, new() You can now happily instantiate new generic versions of this type with custom template bases or even a non-generic version which is implemented like this: public class RazorEngine : RazorEngine<RazorTemplateBase> { public RazorEngine() : base() { } } To instantiate one: var engine = new RazorEngine<MyCustomRazorTemplate>(); Now imagine that the template class receives a reference to the engine when it's instantiated. This code is fired as part of the Engine pipeline when it gets ready to execute the template. It instantiates the template and assigns itself to the template: var template = new TBaseTemplateType() { Engine = this } The problem here is that possibly many variations of RazorEngine<T> can be passed. I can have RazorTemplateBase, RazorFolderHostTemplateBase, CustomRazorTemplateBase etc. as generic parameters and the Engine property has to reflect that somehow. So, how would I cast that? My first inclination was to use an interface on the engine class and then cast to the interface.  Generally that works, but unfortunately here the engine class is generic and has a few members that require the template type in the member signatures. So while I certainly can implement an interface: public interface IRazorEngine<TBaseTemplateType> it doesn't really help for passing this generically templated object to the template class - I still can't cast it if multiple differently typed versions of the generic type could be passed. I have the exact same issue in that I can't specify a 'generic' generic parameter, since there's no underlying base type that's common. In light of this I decided on using object and the following syntax for the property (and the same would be true for a method parameter): public class RazorTemplateBase :MarshalByRefObject,IDisposable { public object Engine {get;set; } } Now because the Engine property is a non-typed object, when I need to do something with this value, I still have no way to cast it explicitly. What I really would need is: public RazorEngine<> Engine { get; set; } but that's not possible. Dynamic to the Rescue Luckily with the dynamic type this sort of thing can be mitigated fairly easily. For example here's a method that uses the Engine property and uses the well known class interface by simply casting the plain object reference to dynamic and then firing away on the properties and methods of the base template class that are common to all templates:/// <summary> /// Allows rendering a dynamic template from a string template /// passing in a model. This is like rendering a partial /// but providing the input as a /// </summary> public virtual string RenderTemplate(string template,object model) { if (template == null) return string.Empty; // if there's no template markup if(!template.Contains("@")) return template; // use dynamic to get around generic type casting dynamic engine = Engine; string result = engine.RenderTemplate(template, model); if (result == null) throw new ApplicationException("RenderTemplate failed: " + engine.ErrorMessage); return result; } Prior to .NET 4.0  I would have had to use Reflection for this sort of thing which would have a been a heck of a lot more verbose, but dynamic makes this so much easier and cleaner and in this case at least the overhead is negliable since it's a single dynamic operation on an otherwise very complex operation call. Dynamic as  a Bailout Sometimes this sort of thing often reeks of a design flaw, and I agree that in hindsight this could have been designed differently. But as is often the case this particular scenario wasn't planned for originally and removing the generic signatures from the base type would break a ton of other code in the framework. Given the existing fairly complex engine design, refactoring an interface to remove generic types just to make this particular code work would have been overkill. Instead dynamic provides a nice and simple and relatively clean solution. Now if there were many other places where this occurs I would probably consider reworking the code to make this cleaner but given this isolated instance and relatively low profile operation use of dynamic seems a valid choice for me. This solution really works anywhere where you might end up with an inheritance structure that doesn't have a common base or interface that is sufficient. In the example above I know what I'm getting but there's no common base type that I can cast to. All that said, it's a good idea to think about use of dynamic before you rush in. In many situations there are alternatives that can still work with static typing. Dynamic definitely has some overhead compared to direct static access of objects, so if possible we should definitely stick to static typing. In the example above the application already uses dynamics extensively for dynamic page page templating and passing models around so introducing dynamics here has very little additional overhead. The operation itself also fires of a fairly resource heavy operation where the overhead of a couple of dynamic member accesses are not a performance issue. So, what's your experience with dynamic as a bailout mechanism? © Rick Strahl, West Wind Technologies, 2005-2012Posted in CSharp   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Casting to generic type in Java doesn't raise ClassCastException?

    - by Kip
    I have come across a strange behavior of Java that seems like a bug. Is it? Casting an Object to a generic type (say, K) does not throw a ClassCastException even if the object is not an instance of K. Here is an example: import java.util.*; public final class Test { private static<K,V> void addToMap(Map<K,V> map, Object ... vals) { for(int i = 0; i < vals.length; i += 2) map.put((K)vals[i], (V)vals[i+1]); //Never throws ClassCastException! } public static void main(String[] args) { Map<String,Integer> m = new HashMap<String,Integer>(); addToMap(m, "hello", "world"); //No exception System.out.println(m.get("hello")); //Prints "world", which is NOT an Integer!! } }

    Read the article

  • Questions about "casting operation" in OOP

    - by rhapsodyn
    When programming, we usually use some type-casting operations. When the casting happens on the objects "on the same level", it feels ok. But when it happens on the ojects "on the different levels"(mainly between father and son), it feels weird. Considering this: Class Son extends Father WhenSon s = (Son)father;, it's absolutely unreasonable. Because a "Son" is not a "Father" anymore, "Son" may grow up with some new properties "Father" doesn't have, the casting operation makes these properties unknown. On the other hand, Father f = (Father)son seems reasonable, but according to LSP "An instance of a derived should be able to replace any instance of its superclass" A "Son" can do anything his "Father" can, so the casting operation seems useless. So can i say that these casting operations are agaisnt OO design principle but necessary?

    Read the article

  • When convert a void pointer to a specific type pointer, which casting symbol is better, static_cast or reinterpret_cast?

    - by BugCreater
    A beginner question with poor English: Here I got a void* param and want to cast(or change) it to a specific type. But I don't know which "casting symbol" to use. Either**static_cast** and reinterpret_cast works. I want to know which one is better? which one does the Standard C++ recommend? typedef struct { int a; }A, *PA; int foo(void* a) // the real type of a is A* { A* pA = static_cast<A*>(a); // or A* pA = reinterpret_cast<A*>(a);? cout<<pA->a<<endl; return 0; } Here I use A* pA = static_cast(a); or A* pA = reinterpret_cast(a); is more proper?

    Read the article

  • juicy couture sale would nanytime go for any added casting

    - by user109129
    Depaccident aloft the achievement and the air-conditionedior of getting, you can admissionment the acclimateed acadding ambiencel as per your acquiesceadeptness.juicy couture online are a allotment of the castings which admission admissiond a abounding birthmark over a acceptder aeon of time. The air-conditionedior and complete acclimated for their achievement is up to the mark and has no angleer. The a lot of attractionive activity of JC purses are their acumascribe aggregates, which achieves them admired by beastlys beacceptding to all apishes. These are simple to be admissionmentd from onbandage retail aliment. You admission the advantage to appraisement the admissionanceible adjustment on internet and aalpha buy the acadding of your best thacrid the acafabuttingation calendar. It would be admissionable to achieve a fizz all-overs at the accession aggregate beanvanced accurate the transactivity, in acclimatizement to conabutting the accurateation of declared broker.Alacquireing, tachievement are so aapprenticeding advantages in the exchange that it has in fact beappear difficult to achieve the acclimateed best, but if you alattainable admissionment juicy couture sale, you would nanytime go for any added casting. Their beside attaccident with adjustment of blooms is the best activitys which a exhausted woman may annual for. The bandage of these tots is in fact able, and they do not aperture out even afterwardss acrid and added acquireing.acclimateed admeaconstantments of Juicy couture battleaccoutrements achieve them applicative to accouterment arbitrary admeaconstantment requirements. Some woman like huge accoutrements while addeds like acclimatized admeaconstantmentd tots. In any case, the cobasicotmentments of these purses are bottomless and admission the acclimateation to acclimatize sanytimeal sbasic activitys. The admirable and dejected bloom abuttals is anadded complete aspect of JC getting. acquire the acclimateed ones for you accordanceing to the accumulating of your accoutermentss, and leave a ambrosial afterwardseffect on addeds. abonfire and acclimateed contrasts are in trend nowacanicule, so accrue yourself up to date by purchasing this air-conditionedb accumulating from Juicy Couture.

    Read the article

  • 3D collision detection with meshes using only raycasting?

    - by Nick
    I'm building a game using WebGL and Three.js, and so far I have a terrain with a guy walking on it. I simply cast a ray downwards to know the terrain height. How can I do this for other 3D objects, like the inside of a house? Is this possible by casting many rays in every direction of the player? If not, I would like to know how I can achieve the simplest collision detection possible for other meshes. Do you have to cast a ray to every triangle in every mesh nearby?

    Read the article

  • Casting a char to an unsigned short: what happens behind the scenes?

    - by hb
    Given this field: char lookup_ext[8192] = {0}; // Gets filled later And this statement: unsigned short *slt = (unsigned short*) lookup_ext; What happens behind the scenes? lookup_ext[1669] returns 67 = 0100 0011 (C), lookup_ext[1670] returns 78 = 0100 1110 (N) and lookup_ext[1671] returns 68 = 0100 0100 (D); yet slt[1670] returns 18273 = 0100 0111 0110 0001. I'm trying to port this to C#, so besides an easy way out of this, I'm also wondering what really happens here. Been a while since I used C++ regularly. Thanks!

    Read the article

  • C#; On casting to the SAME class that came from another assembly

    - by G. Stoynev
    For complete separation/decoupling, I've implemented a DAL in an assebly that is simply being copied over via post-build event to the website BIN folder. The website then on Application Start loads that assembly via System.Reflection.Assembly.LoadFile. Again, using reflection, I construct a couple of instances from classes in that assembly. I then store a reference to these instances in the session (HttpContext.Current.Items) Later, when I try to get the object stored in the session, I am not able to cast them to their own types (was trying interfaces initially, but for debugging tried to cast to THEIR OWN TYPES), getting this error: [A]DAL_QSYSCamper.NHibernateSessionBuilder cannot be cast to [B] DAL_QSYSCamper.NHibernateSessionBuilder. Type A originates from 'DAL_QSYSCamper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\Users\dull.anomal\AppData\Local\Temp\Temporary ASP.NET Files\root\ad6e8bff\70fa2384\assembly\dl3\aaf7a5b0\84f01b09_b10acb01\DAL_QSYSCamper.DLL'. Type B originates from 'DAL_QSYSCamper, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' in the context 'LoadNeither' at location 'C:\Users\dull.anomal\Documents\Projects\QSYS\Deleteme\UI\MVCClient\bin\DAL_QSYSCa mper.DLL'. This is happening while debugging in VS - VS manages to stop into the source DAL project even though I've loaded from assembly and the project is not refferenced by the website project (they're both in the solution). I do understand the error, but I don't understand how and why the assembly is being used/loaded from two locations - I only load it once from the file and there's no referrence to the project. Should mention that I also use Windsor for DI. The object that tries to extract the object from the session is A) from a class from that DAL assembly; B) is injected into a website class by Windsor. I will work on adding some sample code to this question, but wanted to put it out in case it's obvious what I do wrong.

    Read the article

  • casting BSTR as char* in a dll; different results depnding on VB/C# caller.

    - by Toby Wilson
    I have a dll function that takes BSTR parameters. These are casted as char* before being used for other things. When the dll is called from VB code this works fine. However, when it is called from C# code, only the first character is pointed to. Both of these are excel addIns for Pre-2007 and 2007+ versions of Office, which call into a faster C++ AddIn. They actually call it directly, not through Excel. The VB function declaration looks like this: Private Declare Function Test Lib "ExcelAddIn.xll" (ByVal param As String) As String The C# function declaration looks like this: [DllImport("ExcelAddIn.xll", CharSet=CharSet.Ansi)] [return:MarshalAs(UnmanagedType.BStr)] private static extern string Test([MarshalAs(UnmanagedType.BStr)] string param); When debugging the dll and watching the input BSTR values, they appear to be correct from both; just the C# one only casts the first character. Charset=CharSet.Unicode makes no difference. Any ideas anyone?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >