开发者

List.Contains Suspicious Call

I am attempting to run a while loop based on if a char array contains a given char. I thought I could accomplish this with the following:

while(Arrays.asList(letterMatrix).contains(keyword.charAt(i-1)))

Where letterMatrix is a char [][] and keyword is a String.

But I get the following warning in NetBeans: Suspicious call to java.util.Collection.contains: Given object cannot contain instances of char (expected char[]).

I'm a java novice, but I interpret this to mean that .contains is expecting an array, and I don't see why that w开发者_JAVA技巧ould be.

What am I missing?


Arrays.asList(char[][]) will return List<char[]>, figure out now :)


Firstly, you probably don't want to call Arrays.asList(...) in your while loop declaration; this method returns a new ArrayList on each invocation. Also, as the other answers suggest, the returned value will be a List<char[]>. So, try:

public void testTwoDimAsList() {
    char[][] arr = new char[][]{{'a', 'b', 'c'}, {'1', '2', '3'}};
    List<char[]> asList = Arrays.asList(arr);
    // ...
}

Of course, the running time of #contains in an array list is linear, and that may not be optimal either.


Cosmin and Tnem have already pointed out why that warning is justified, as it indeed indicates a bug. Here's how to fix it:

boolean contains(char[][] matrix, char wanted) {
    for (char[] line : matrix) {
        for (char c : line) {
            if (c == wanted) {
                return true;
            }
        }
    }
}

while (contains(letterMatrix, keyword.charAt(i-1)) {
    ....
}

Of course, as the two nested loop hint at, this solution will be somewhat slow if the matrix is big. A data structure supporting efficient lookups might be called for.


How about. Arrays.deepToString(letterMatrix).contains("" + keyword.charAt(i-1));
For your case this is the fastest method. It turns your matrix into a String and then searches your char in it.


Arrays.asList(letterMatrix) will produce this object List<Char[]>, if you look at the method contains() it expects the object you are looking for to match the type of the list, so you are looking for a char in a list of arrays of char.

EDIT: see comments

List<Character> checkList = new ArrayList<Character>();
for(char[] charArray : letterMatrix) {
    for(char aChar : charArray) {
        checkList.add(aChar);
    }
}
while(checkList.contains(keyword.charAt(i-1)));


Okay so basically what you need to understand is char[] cannot be compared to the PDT char.

You must iterate through the newly made list and create new lists on top of that.

e.g.

while(Arrays.asList(Arrays.asList(letterMatrix).get(x)).contains(keyword.charAt(i-1)))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜