Follow-up: Find number of times that difference of array values are equals to a number This question is follow-up to this question.

Sample Calculation


10-21=-11
10-34=-24
10-45=-35
10-56=-46
21-10=11     &lt;
21-34=-13
21-45=-24
21-56=-35
34-10=24
34-21=13
34-45=-11
34-56=-22
45-10=35
45-21=24
45-34=11   &lt;&lt;
45-56=-11
56-10=46
56-21=35
56-34=22
56-45=11   &lt;&lt;&lt;



Code

Set&lt;Integer&gt; tchars = new HashSet&lt;&gt;();
        tchars.add(10);
        tchars.add(21);
        tchars.add(34);
        tchars.add(45);
        tchars.add(56);
        int number = 11;
        int counter = 0;

        Iterator it = tchars.iterator();
        while (it.hasNext()) {
            Integer inte = (Integer) it.next();
            if (tchars.contains(inte + number)) {
                System.err.println(inte + " " + number);
                counter++;
            }
        }
        System.err.println(counter);
Using a Set is problematic.  

First, as pointed out on the original question in @Vogel612's comment, it restricts duplicate values. Second, it also makes your code a lot messier, as you're now grabbing an Iterator, calling .hasNext(), and testing in a while loop instead of using more concise syntax.

I'd just use a List&lt;Integer&gt;, get rid of all the casts, and use a for-each style syntax instead of using the Iterator. Finally, number and counter aren't very meaningful as variable names in the context of this snippet.  If they are meaningful in the wider context of wherever this came from so-be-it, but I find something more along the lines of difference and result much clearer.

Something more like this:

List&lt;Integer&gt; tchars = Arrays.asList(10, 21, 34, 45, 56);
int difference = 11;
int result = 0;

for (int test : tchars) {
    if (tchars.contains(test + difference)) {
        System.err.println(test + " " + difference);
        result++;
    }
}

System.err.println(result);


Dead simple, and you can see immediately what it is doing.