Java报错Cannot resolve method 'contains(int)',数组包含判断异常求助
问题原因与解决方案
核心问题分析
- 编译错误原因:
Arrays.asList(YEARS)传入int[]时,不会将数组的每个int元素拆分为List的元素,而是把整个int[]对象作为List的唯一元素,生成的是List<int[]>类型。而contains(int)方法不存在,因为List存储的是数组对象,不是Integer类型,参数类型不匹配导致报错。 - 逻辑错误原因:即使忽略编译错误,
contains(year)判断的是List中是否存在Integer类型的year,但List里实际存的是int[]对象,两者类型完全不同,必然返回false,所以输出"Not contains"。
修复方案
方案1:将数组改为Integer类型
把原int[]替换为Integer[],这样Arrays.asList会正确生成List<Integer>,contains方法可以正常工作:
private static final Integer[] YEARS = new Integer[] { 1881, 1893, 1900, 1910, 1919, 1923, 1930, 1932, 1934, 1938 }; public static void main(String[] args) { int year = 1919; if (Arrays.asList(YEARS).contains(year)) { System.out.println("Contains"); } else { System.out.println("Not contains"); } }
方案2:使用Java Stream API判断
无需修改原数组类型,通过流操作直接判断元素是否存在:
private static final int[] YEARS = new int[] { 1881, 1893, 1900, 1910, 1919, 1923, 1930, 1932, 1934, 1938 }; public static void main(String[] args) { int year = 1919; if (Arrays.stream(YEARS).anyMatch(y -> y == year)) { System.out.println("Contains"); } else { System.out.println("Not contains"); } }
方案3:使用Arrays.binarySearch(适用于有序数组)
原数组是升序排列的,可通过二分查找判断元素是否存在:
private static final int[] YEARS = new int[] { 1881, 1893, 1900, 1910, 1919, 1923, 1930, 1932, 1934, 1938 }; public static void main(String[] args) { int year = 1919; if (Arrays.binarySearch(YEARS, year) >= 0) { System.out.println("Contains"); } else { System.out.println("Not contains"); } }
内容的提问来源于stack exchange,提问作者atılgan
相关产品推荐
相关产品推荐

