ArrayList contains case sensitivity

前端 未结 19 1771
故里飘歌
故里飘歌 2020-11-27 17:14

I am currently using the contains method belonging to the ArrayList class for making a search. Is there a way to make this search case insensitive in java? I found that in C

19条回答
  •  一生所求
    2020-11-27 17:59

    Another solution:

    public class IgnorecaseList extends ArrayList{
    
        @Override
        public boolean contains(Object o) {
            return indexOf(o) >= 0;
        } 
    
        @Override
        public int indexOf(Object o) {
            if(o instanceof String){
                for (int i = 0; i < this.size(); i++) {
                    if(((String)o).equalsIgnoreCase(get(i))){
                        return i;
                    }
                }
            }
            return -1;
        }
    }
    

    contains() method uses indexOf... In this sollution you can also know in where position is the string. list.add("a") -> list.indexOf("A") == 0 or list.indexOf("a") == 0 ..

    You should also consider using a Set instead of List.

提交回复
热议问题