目錄
2. Binary Search (for sorted arrays)
3. Using ArrayList or Collections (alternative approach)
4. Using Streams (Java 8 )
首頁 Java java教程 您如何在Java中的數組中搜索元素?

您如何在Java中的數組中搜索元素?

Sep 02, 2025 am 02:03 AM
java 陣列

在Java中搜索數組元素的最佳方法取決於數組是否已排序及性能需求:對於未排序的小數組,使用線性搜索(時間複雜度O(n));對於已排序數組,使用Arrays.binarySearch()(時間複雜度O(log n));若使用對像數組且追求簡潔,可轉為List後調用contains()或indexOf();在Java 8 中偏好函數式風格時,可使用Arrays.stream().anyMatch()實現簡潔的一行代碼,但性能略低於傳統循環,因此選擇方法需權衡性能、可讀性和數據是否排序的情況。

How do you search for an element in an array in Java?

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() returns true or false .
  • list.indexOf(30) returns the index or -1 if not found.
  • Note: Works with wrapper types ( Integer[] ), not primitive arrays like int[] .

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() returns true 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 use contains .
  • 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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Stock Market GPT

Stock Market GPT

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

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

如何在PHP中的數組中找到一個元素? 如何在PHP中的數組中找到一個元素? Sep 07, 2025 am 06:45 AM

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

wi-fi打電話不工作 wi-fi打電話不工作 Sep 05, 2025 am 04:44 AM

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

如何將對象轉換為PHP中的數組? 如何將對象轉換為PHP中的數組? Sep 14, 2025 am 03:14 AM

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

記事本如何更改案例(大寫/小寫) 記事本如何更改案例(大寫/小寫) Sep 03, 2025 am 09:22 AM

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

如何檢查陣列在PHP中是關聯還是順序? 如何檢查陣列在PHP中是關聯還是順序? Sep 16, 2025 am 05:40 AM

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

如何在Java中實現可比接口? 如何在Java中實現可比接口? Sep 16, 2025 am 03:44 AM

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

如何從Java中的字符串中獲取文件擴展名? 如何從Java中的字符串中獲取文件擴展名? Sep 16, 2025 am 03:40 AM

togetafilextensionInjava,uselastIndexof()tofindthelastDotAndAndExtractthesubStringFerit,確保theDotiS notatIs notatIndex0orabsent; forcleanercode,useapachecommonsio’sfileNameutils.getExtension()

壓縮(zipper)文件夾錯誤:訪問被拒絕[固定] 壓縮(zipper)文件夾錯誤:訪問被拒絕[固定] Sep 06, 2025 am 06:16 AM

Ifyougetan"AccessDenied"errorwhenopeningazippedfolder,trythesesteps:1.RunFileExplorerasAdministrator.2.Takeownershipofthefolder.3.Modifypermissionstoallowfullcontrol.4.Copythefiletoauser-accessiblelocation.5.UseCommandPrompttoextract(tar-xf

See all articles