B M
B M

Reputation: 671

Testing set membership in Java

I am confused as to why the following method to test set membership is not working in my program. If I run the following program with any text file as the argument, in the output I only see "Second". I thought both if statements should be testing the same thing.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;



public class Exc0 {

    public static void main(String args[]){
        try {
            File input = new File(args[0]);
            BufferedReader reader = new BufferedReader(new FileReader(input));
            int[] delimiters = {' ', '(', ',', ')'};

            int current;
            while ((current = reader.read()) != -1){
                if ((Arrays.asList(delimiters).contains(current))){
                    System.out.println("First");
                }
                if (current == ' ' || current == '(' || current == ',' || current == ')'){
                    System.out.println("Second");
                }
            }


        }
        catch (IOException e){
            e.printStackTrace();
        }
    }

}

Upvotes: 1

Views: 575

Answers (2)

Markus A.
Markus A.

Reputation: 12752

(Corrected based on other answer)

Since there is no List<int>, Arrays.asList(int[] something) can not return what you are hoping for. While, at first I thought, it would instead return a List<Integer>, this is not the case. As dasblinkenlight pointed out, it will actually return a List<int[]> with one element instead. (Therefore, declaring current as an Integer instead of an int will not fix the bug, but declaring delimiters as an Integer[] probably will as suggested by Marc Baumbach in the comments.)

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

This happens because when you call Arrays.asList(delimiters) you get a list with a single instance of int[], not with four instances of int/Integer.

In general, for checking membership in sets of characters you may be better of with a String:

String delimiters = "() ,";
if (delimiters.indexOf(current) >= 0) {
    System.out.println("First");
}

Upvotes: 3

Related Questions