Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array in Java program bizarre behaviour [duplicate]

Tags:

java

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.

like image 248
Umesh K Avatar asked Dec 10 '22 10:12

Umesh K


2 Answers

Did you noticed that 012 (octal) is 10 (decimal) ?

like image 171
PeterMmm Avatar answered Dec 28 '22 00:12

PeterMmm


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.

like image 39
Can't Tell Avatar answered Dec 28 '22 00:12

Can't Tell