Java程序中的数组奇怪的行为 [英] Array in Java program bizarre behaviour
问题描述
我遇到了这个Java程序,它以意想不到的方式运行。以下程序计算int数组中元素对之间的差异。
I came across this Java program and its behaving in unexpected way. The following program computes the differences between pairs of elements in an int array.
import java.util.*;
public class SetTest
{
public static void main(String[] args)
{
int vals[] = {786,678,567,456,
345,234,123,012};
Set<Integer> diffs = new HashSet<Integer>();
for(int i=0; i < vals.length ; i++)
for(int j = i; j < vals.length; j++)
diffs.add(vals[i] - vals[j]);
System.out.print(diffs.size());
}
}
如果我们分析它似乎设定的大小应为8是数组的大小。但是,如果你运行这个程序,它打印14.发生了什么?任何的想法?
If we analyze it seems set size should be 8 which is the size of the array. But if you ran this program it prints 14. What's going on? Any idea?
提前谢谢你。
答案:出现这种奇怪的行为是因为如果我们将数组改为12则数组中的012变为八进制,然后按预期打印8。
Answer: This strange behavior happens because 012 in the array becomes octal if we change it to 12 then it prints 8 as expected.
课程:永远不要用零填充整数文字。
Lesson: Never pad an integer literal with zeros.
推荐答案
您是否注意到 012 (八进制)是10(十进制) ?
Did you noticed that 012 (octal) is 10 (decimal) ?
这篇关于Java程序中的数组奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!