EzDevInfo.com

casting

Delegate methods in Ruby and preserve self. Add behaviors to your objects without altering their superclass heirarchy.

Why does an NSInteger variable have to be cast to long when used as a format argument?

NSInteger myInt = 1804809223;
NSLog(@"%i", myInt); <==== 

The code above produces an error:

Values of type "NSInteger" should not be used as format arguments: add an explicit cast to 'long' instead.

The correct NSLog message is actually NSLog(@"%lg", (long) myInt); Why do I have to convert the integer value of myInt to long if I want the value to display?


Source: (StackOverflow)

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

What are the proper uses of:

  • static_cast
  • dynamic_cast
  • const_cast
  • reinterpret_cast
  • C-style cast (type)value
  • Function-style cast type(value)

How does one decide which to use in which specific cases?


Source: (StackOverflow)

Advertisements

Safely casting long to int in Java

What's the most idiomatic way in Java to verify that a cast from long to int did not lose any information?

This is my current implementation:

public static int safeLongToInt(long l) {
    int i = (int)l;
    if ((long)i != l) {
        throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
    }
    return i;
}

Source: (StackOverflow)

How to convert an array to object in PHP?

How can i convert an array like this to object?

    [128] => Array
        (
            [status] => Figure A.
 Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
        )

    [129] => Array
        (
            [status] => The other day at work, I had some spare time
        )

)

Source: (StackOverflow)

Do I cast the result of malloc?

In this question, someone suggested in a comment that I should not cast the results of malloc, i.e:

int *sieve = malloc(sizeof(int)*length);

rather than:

int *sieve = (int *)malloc(sizeof(int)*length);

Why would this be the case?


Source: (StackOverflow)

How do I check if a string is a number (float) in Python?

What is the best possible way to check if a string can be represented as a number in Python?

The function I currently have right now is:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling float in the main function is even worse.


Source: (StackOverflow)

How do you cast a List of supertypes to a List of subtypes?

For example, lets say you have two classes:

public class TestA {}
public class TestB extends TestA{}

I have a method that returns a List<TestA> and I would like to cast all the objects in that list to TestB so that I end up with a List<TestB>.


Source: (StackOverflow)

C# - Assignment in an if statement

I have a class Animal, and its subclass Dog. I often find myself coding the following lines:

if (animal is Dog)
{
    Dog dog = animal as Dog;    
    dog.Name;    
    ... 
}

For the variable Animal animal;.

Is there some syntax that allows me to write something like:

if (Dog dog = animal as Dog)
{    
    dog.Name;    
    ... 
}

Source: (StackOverflow)

How to convert a factor to an integer\numeric without a loss of information?

When I convert a factor to a numeric or integer, I get the underlying level codes, not the values as numbers.

f <- factor(sample(runif(5), 20, replace = TRUE))
##  [1] 0.0248644019011408 0.0248644019011408 0.179684827337041 
##  [4] 0.0284090070053935 0.363644931698218  0.363644931698218 
##  [7] 0.179684827337041  0.249704354675487  0.249704354675487 
## [10] 0.0248644019011408 0.249704354675487  0.0284090070053935
## [13] 0.179684827337041  0.0248644019011408 0.179684827337041 
## [16] 0.363644931698218  0.249704354675487  0.363644931698218 
## [19] 0.179684827337041  0.0284090070053935
## 5 Levels: 0.0248644019011408 0.0284090070053935 ... 0.363644931698218

as.numeric(f)
##  [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2

as.integer(f)
##  [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2

I have to resort to paste to get the real values.

as.numeric(paste(f))
##  [1] 0.02486440 0.02486440 0.17968483 0.02840901 0.36364493 0.36364493
##  [7] 0.17968483 0.24970435 0.24970435 0.02486440 0.24970435 0.02840901
## [13] 0.17968483 0.02486440 0.17968483 0.36364493 0.24970435 0.36364493
## [19] 0.17968483 0.02840901

Is there a better way to convert a factor to numeric?


Source: (StackOverflow)

Any idea why I need to cast an integer literal to (int) here?

In the following example

int i = -128;
Integer i2 = (Integer) i; // compiles

Integer i3 = (Integer) -128; /*** Doesn't compile ***/

Integer i4 = (Integer) (int) -128; // compiles
Integer i4 = -128; // compiles
Integer i5 = (int) -128; // compiles
Integer i6 = (Integer) (-128); // compiles
Integer i7 = (Integer) 0-128; // compiles

I can't cast -128 with (Integer) but I can cast (int) -128.

I always thought -128 was of int type and casting it with (int) should be redundant.

The error on the line with i3 is

cannot find symbol variable Integer

I tried this with Java 6 update 29 and Java 7 update 1.

EDIT: You get the same behaviour with +128 instead of -128. It does appear to be confusion between unary and binary operators.


Source: (StackOverflow)

Downcasting in Java

Upcasting is allowed in Java, however downcasting gives a compile error.

The compile error can be removed by adding a cast but would anyway break at the runtime.

In this case why Java allows downcasting if it cannot be executed at the runtime?
Is there any practical use for this concept?

public class demo {
  public static void main(String a[]) {
      B b = (B) new A(); // compiles with the cast, 
                         // but runtime exception - java.lang.ClassCastException
  }
}

class A {
  public void draw() {
    System.out.println("1");
  }

  public void draw1() {
    System.out.println("2");
  }
}

class B extends A {
  public void draw() {
    System.out.println("3");
  }
  public void draw2() {
    System.out.println("4");
  }
}

Source: (StackOverflow)

How do I convert from int to Long in Java?

I keep finding both on here and Google people having troubles going from long to int and not the other way around. Yet I'm sure I'm not the only one that has run into this scenario before going from int to Long.

The only other answers I've found were "Just set it as Long in the first place" which really doesn't address the question.

Can someone help me out here? I initially tried casting but I get a "Cannot cast from int to Long"

for (int i = 0; i < myArrayList.size(); ++i ) {
    content = new Content();
    content.setDescription(myArrayList.get(i));
    content.setSequence((Long) i);
    session.save(content);
}

As you can imagine I'm a little perplexed, I'm stuck using int since some content is coming in as an ArrayList and the entity for which I'm storing this info requires the sequence number as a Long.

Thanks!


Source: (StackOverflow)

Direct casting vs 'as' operator?

Consider the following code:

void Handler(object o, EventArgs e)
{
   // I swear o is a string
   string s = (string)o; // 1
   //-OR-
   string s = o as string; // 2
   // -OR-
   string s = o.ToString(); // 3
}

What is the difference between the three types of casting(okay, 3rd one is not a casting, but you get the intent... ), and which one should be preferred?


Source: (StackOverflow)

Cast Double to Integer in Java

Any way to cast java.lang.Double to java.lang.Integer?

It throws an exception

"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer"


Source: (StackOverflow)

Differences in auto-unboxing between Java 6 vs Java 7

Hi I have noted a difference in auto unboxing behavior between Java SE 6 and Java SE 7. I'm wondering why that is, because I can't find any documentation of changes in this behavior between these two versions.

Here's a simple example:

Object[] objs = new Object[2];
objs[0] = new Integer(5);
int myInt = (int)objs[0];

This compiles fine with javac from Java SE 7. However, if I give the compiler the "-source 1.6" argument I get an error on the last line:

inconvertible types
found   : java.lang.Object
required: int

I tried downloading the Java SE 6 to compile with the native version 6 compiler (without any -source option). It agrees and gives the same error as above.

So what gives? From some more experimentation it seems that the unboxing in Java 6 can only unbox values that clearly (at compile time) is of the boxed type. For instance, this works in both versions:

Integer[] objs = new Integer[2];
objs[0] = new Integer(5);
int myInt = (int)objs[0];

So it seems that between Java 6 and 7, the unboxing feature was enhanced so that it could cast and unbox object types in one swoop, without knowing (at compile time) that the value is of the proper boxed type. However, reading through the Java Language Specification or blog postings that were written at the time Java 7 came out, I can't see any change of this thing, so I'm wondering what the change is and what this "feature" is called?

Just a curiosity: Due the change, it is possible to trigger "wrong" unboxings:

Object[] objs = new Float[2];
objs[0] = new Float(5);
int myInt = (int)objs[0];

This compiles fine but gives a ClassCastException at runtime.

Hope someone can help me with a reference on this. Thank you in advance.


Source: (StackOverflow)