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());
}
}
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?
Thank you in advance.
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.
Did you noticed that 012 (octal) is 10 (decimal) ?
Since you are running two nested loops the add()
method is called multiple times. Since a set cannot contain duplicate objects the number of values in the set will be the number of unique values. The add()
function returns true if the set did not already contain the element and false if the set already had the element.
Change the line
diffs.add(vals[i] - vals[j]);
to
System.out.println((diffs.add(vals[i] - vals[j])));
to see what I mean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With