在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
当前回答
有趣的自动装箱和Java中的整数缓存:
Integer foo = 1000;
Integer bar = 1000;
foo <= bar; // true
foo >= bar; // true
foo == bar; // false
//However, if the values of foo and bar are between 127 and -128 (inclusive)
//the behaviour changes:
Integer foo = 42;
Integer bar = 42;
foo <= bar; // true
foo >= bar; // true
foo == bar; // true
解释
快速浏览一下Java源代码将会出现以下内容:
/**
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Integer(int)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
*
* @param i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= -128 && i <= IntegerCache.high)
return IntegerCache.cache[i + 128];
else
return new Integer(i);
}
注意:IntegerCache。High默认为127,除非由属性设置。
自动装箱的情况是,foo和bar都是从缓存中检索到相同的整数对象,除非显式创建:例如,foo = new integer(42),因此在比较引用是否相等时,它们将为真而不是假。比较Integer值的正确方法是使用.equals;
其他回答
在ColdFusion中,文本值自动转换为各种数据类型,用于各种目的。我遇到了一个奇怪的问题,“00A”和“000”被返回为相等。事实证明,ColdFusion将“00A”解释为时间,转换为某种数字时间格式,并将其转换为0。“000”被转换为0。所以它们都被认为是相等的。那时我学习了字符串的比较函数。
foo是什么数据类型?
SELECT TOP 1
NULL AS foo
INTO
dbo.bar
FROM
sys.columns --trivial
为什么所有东西都归零?
SELECT CAST('' AS int), CAST('' AS datetime), CAST('' AS float)
...除了这
SELECT CAST('' AS decimal)
为什么c#的List<T>.AddRange()不让我添加T的子类型的元素?阀门列表< T > () ! 微软只需要多写一行代码:
public void AddRange<S>(
IEnumerable<S> collection
) where S : T
在c++中,你可以做:
std::string my_str;
std::string my_str_concat = my_str + "foo";
但你不能:
std::string my_str_concat = "foo" + my_str;
操作符重载通常服从WTF。
在Python中:
abs((10+5j)-(25+-5j))
返回~18.03,根据毕达哥拉斯定理,这是点(10,5)和(25,5)之间的距离。之所以会出现这种情况,是因为Python的原生语言支持2+2j形式的复数。由于复数的绝对值形式为a+bj =根号下(a^2+b^2),我们得到距离,同时从一个复数减去另一个复数,然后应用abs(绝对)函数在它上面。