Java Integer数组调用contains(int)方法报错:找不到符号的解决方法
Hey there! Let's break down why you're hitting this error and fix it step by step.
Why the Error Occurs
The issue is simple: Java arrays (like your Integer[] bag) don’t have a built-in contains() method. That method belongs to Java’s Collection Framework—think classes like ArrayList, HashSet, or LinkedList—not plain old arrays. So when you try to call bag.contains(int), the compiler has no idea what you’re referring to.
3 Straightforward Solutions
Here are three easy ways to check if your array contains a target value:
1. Convert the Array to a List
The quickest fix is to turn your Integer[] into a List<Integer> using Arrays.asList(), which gives you access to the contains() method. Note that Arrays.asList() returns a fixed-size list—if you need to add/remove elements later, wrap it in an ArrayList:
import java.util.Arrays; import java.util.List; public class ArrayCheckExample { public static void main(String[] args) { Integer[] bag = {5, 10, 15, 20}; // Fixed-size list (good for read-only operations) List<Integer> bagList = Arrays.asList(bag); if (bagList.contains(10)) { System.out.println("Value found in the array!"); } // Mutable list (use if you need to modify the collection later) // List<Integer> mutableBag = new ArrayList<>(Arrays.asList(bag)); } }
2. Write a Custom Loop Method
If you want to stick with arrays and avoid collections, loop through the array manually. This lets you handle edge cases like null values in your Integer[] safely:
public class ArrayCheckExample { public static boolean doesArrayContain(Integer[] array, int target) { for (Integer num : array) { // Check for null first to avoid NullPointerException if (num != null && num == target) { return true; } } return false; } public static void main(String[] args) { Integer[] bag = {5, 10, 15, 20}; if (doesArrayContain(bag, 15)) { System.out.println("Value found!"); } } }
3. Use Java Streams (Java 8+)
For modern, concise code, use streams to check for the value in one line:
import java.util.Arrays; public class ArrayCheckExample { public static void main(String[] args) { Integer[] bag = {5, 10, 15, 20}; boolean hasTarget = Arrays.stream(bag).anyMatch(num -> num == 20); if (hasTarget) { System.out.println("Value exists in the array!"); } } }
Which Solution Should You Pick?
- Go with the List conversion if you’re already working with collections or need other list operations.
- Use the custom loop if you want to stick with arrays and need full control over edge cases.
- Opt for streams if you prefer clean, modern Java syntax (and you’re on Java 8 or newer).
内容的提问来源于stack exchange,提问作者tolgayan

