您如何在Java中的數組中搜索元素?
在Java中搜索數組元素的最佳方法取決於數組是否已排序及性能需求:對於未排序的小數組,使用線性搜索(時間複雜度O(n));對於已排序數組,使用Arrays.binarySearch()(時間複雜度O(log n));若使用對像數組且追求簡潔,可轉為List後調用contains()或indexOf();在Java 8 中偏好函數式風格時,可使用Arrays.stream().anyMatch()實現簡潔的一行代碼,但性能略低於傳統循環,因此選擇方法需權衡性能、可讀性和數據是否排序的情況。
In Java, searching for an element in an array depends on whether the array is sorted or not, and what kind of performance or simplicity you're aiming for. Here are the most common and practical ways:
1. Linear Search (for unsorted arrays)
If the array isn't sorted, the simplest approach is to loop through each element until you find a match.
int[] arr = {10, 20, 30, 40, 50}; int target = 30; boolean found = false; for (int i = 0; i < arr.length; i ) { if (arr[i] == target) { System.out.println("Element found at index " i); found = true; break; } } if (!found) { System.out.println("Element not found"); }
- Works with any array, sorted or not.
- Time complexity: O(n).
- Best when the array is small or unsorted.
2. Binary Search (for sorted arrays)
If the array is sorted, you can use binary search for better performance.
You can use the built-in method from Arrays.binarySearch()
:
import java.util.Arrays; int[] arr = {10, 20, 30, 40, 50}; int target = 30; int index = Arrays.binarySearch(arr, target); if (index >= 0) { System.out.println("Element found at index " index); } else { System.out.println("Element not found"); }
- Only works on sorted arrays.
- Time complexity: O(log n).
- If the array isn't sorted, sort it first using
Arrays.sort(arr)
— but that adds O(n log n) overhead.
⚠️ Important: If you use
binarySearch
on an unsorted array, the result is undefined.
3. Using ArrayList or Collections (alternative approach)
If you're open to using collections instead of raw arrays, you can convert the array to a List
and use contains()
or indexOf()
:
import java.util.Arrays; import java.util.List; Integer[] arr = {10, 20, 30, 40, 50}; List<Integer> list = Arrays.asList(arr); if (list.contains(30)) { System.out.println("Element found"); }
-
contains()
returnstrue
orfalse
. -
list.indexOf(30)
returns the index or -1 if not found. - Note: Works with wrapper types (
Integer[]
), not primitive arrays likeint[]
.
4. Using Streams (Java 8 )
Modern Java allows using streams for more readable one-liners:
import java.util.Arrays; int[] arr = {10, 20, 30, 40, 50}; boolean found = Arrays.stream(arr).anyMatch(x -> x == 30); if (found) { System.out.println("Element found"); }
-
anyMatch()
returnstrue
if any element matches. - You can also use
IntStream
for more operations. - Slightly more overhead than a simple loop, but clean and functional in style.
So, the best method depends on your situation:
- Unsorted array, small size : Use linear search (simple loop).
- Sorted array : Use
Arrays.binarySearch()
. - Want clean syntax and using objects : Convert to
List
and usecontains
. - Using Java 8 and prefer functional style : Use
Arrays.stream()
.
Basically, it's about trade-offs between performance, readability, and whether the data is sorted.
以上是您如何在Java中的數組中搜索元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

要查找數組元素,根據需求選擇函數:in_array()檢查值是否存在,array_search()獲取值對應的鍵,array_key_exists()檢查鍵是否存在。

確保Yourdeviceandcarriersupportwi-ficallingingandinableItinsettings - iphone:設置>電話> wi-ficalling; wi-ficalling; android:android> networkings> network&Internet> Mobilenetwork> Mobilenetwork> Advanced> wi-ficalling; vie-ficalling; converseCarrierComparierComparierCompatibilitialcompatibility and CompleteeMpleteeMpleteEmgeTemEngengedDressre

使用(array)可將簡單對象轉為數組,若含私有或受保護屬性,鍵名會帶特殊字符;對於嵌套對象,應使用遞歸函數遍歷轉換,確保所有層級對像變為關聯數組。

TochangetextcaseinNotepad ,firstselectthetext,thengotoEdit>ConvertCaseToandchoosethedesiredoption:1.UPPERCASE–convertsalltexttouppercase.2.lowercase–convertsalltexttolowercase.3.TitleCase–capitalizesthefirstletterofeachword.4.Sentencecase–capital

anarrayis sequentialifitsKeySmatchAconteGIntegerSequenCestArtingFrom0,consebyComparingArray_keys($ array)withArray_Keys(array_keys($ array));否則,itisassociative。

toimplementComparableInjava,DecoreTheComParetomEthodFornaturAlorArdorArdering.1.implementComparableFace.2.OverRideComParetotototoTotoretNnegative,零,orpositiveValuesbasedonComparison.3.usecollections.3.usort.sort()

togetafilextensionInjava,uselastIndexof()tofindthelastDotAndAndExtractthesubStringFerit,確保theDotiS notatIs notatIndex0orabsent; forcleanercode,useapachecommonsio’sfileNameutils.getExtension()
![壓縮(zipper)文件夾錯誤:訪問被拒絕[固定]](https://img.php.cn/upload/article/001/431/639/175711056270360.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Ifyougetan"AccessDenied"errorwhenopeningazippedfolder,trythesesteps:1.RunFileExplorerasAdministrator.2.Takeownershipofthefolder.3.Modifypermissionstoallowfullcontrol.4.Copythefiletoauser-accessiblelocation.5.UseCommandPrompttoextract(tar-xf
