国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 Java java教程 Java 中的陣列:特徵、用法和實(shí)際場景

Java 中的陣列:特徵、用法和實(shí)際場景

Jan 03, 2025 pm 12:37 PM

Arrays in Java: Characteristics, Usage, and Real-Life Scenarios

本文探討了 Java 中陣列的特性,例如固定大小、高效存取和類型安全,同時(shí)將它們與 ArrayList 等動(dòng)態(tài)集合類型進(jìn)行比較。它還提供了現(xiàn)實(shí)生活中的場景,例如儲(chǔ)存產(chǎn)品數(shù)量、修改每日溫度、對學(xué)生成績進(jìn)行排序等,來展示陣列在 Java 中的實(shí)際應(yīng)用。


在 Java 中,陣列是一種基本資料結(jié)構(gòu),允許開發(fā)人員在單一變數(shù)中儲(chǔ)存相同類型的多個(gè)值。由於其固定大小和直接存取功能,陣列提供了管理和操作資料的有效方法。本文將探討 Java 陣列的特性,將它們與 ArrayList 等其他集合類型進(jìn)行比較,並展示陣列在現(xiàn)實(shí)生活中的用途。了解陣列的屬性和應(yīng)用對於建立高效的 Java 程式至關(guān)重要。

下面列出了 Java 中的陣列特性:

  • 固定大小:一旦定義,陣列的大小就無法改變。
  • 有序:陣列按順序儲(chǔ)存元素,這意味著可以在恆定時(shí)間內(nèi)透過索引存取元素。
  • 效率:存取陣列中的任何元素都是一個(gè)恆定時(shí)間的操作。數(shù)組的記憶體開銷非常低,因?yàn)樗鼈儍?chǔ)存單一類型的資料。
  • 單一類型:Java 陣列是類型化的,這意味著它們只能儲(chǔ)存與陣列聲明中聲明的資料類型相同的元素。

陣列與ArrayList不同,ArrayList是列表,是集合介面的一部分。 Java 中的介面是一種參考類型,類似於類,只能包含常數(shù)、預(yù)設(shè)方法、靜態(tài)方法和巢狀類型(Tutorials Point,n. d.)。對於集合接口,它包括 add()、remove()、get() 和 size() 等方法(Oracle 文檔,n.d.)。這允許不同類型的清單類別(例如 ArrayList、LinkedList 和其他類似 Set 類別)使用這些方法。

請注意,陣列不是集合介面的一部分。換句話說,它們沒有與之關(guān)聯(lián)的方法。

使用陣列的現(xiàn)實(shí)場景

場景 1 在商店中儲(chǔ)存產(chǎn)品數(shù)量:
陣列可用於追蹤商店中不同產(chǎn)品的數(shù)量。例如,陣列的每個(gè)元素代表特定產(chǎn)品的數(shù)量。

public class Main {
    public static void main(String[] args) {
        // Stores product quantities
        int[] quantities = new int[4];   
        // Storing product quantities
        quantities[0] = 50;  
        quantities[1] = 30;  
        quantities[2] = 20;  
        quantities[3] = 40;  
        // Prints the product quantities
        for (int i = 0; i < quantities.length; i++) {
            System.out.println("Product " + (i + 1) + " Quantity: " 
                                                            +   quantities[i]);
        }
    }
}

輸出:

Product 1 Quantity: 50
Product 2 Quantity: 30
Product 3 Quantity: 20
Product 4 Quantity: 40

場景 2:
數(shù)組可用於儲(chǔ)存和修改每日溫度。

public class Main {
    public static void main(String[] args) {
        // Stores daily temperatures 
        int[] temperatures = {68, 70, 75, 72, 69, 71, 73};

        // Prints initial temperatures
        System.out.println("Initial daily temperatures:");
        printTemperatures(temperatures);

        // Modifies temperatures
        modifyTemperature(temperatures, 2, 78);
        modifyTemperature(temperatures, 5, 74);

        // Prints updated temperatures
        System.out.println("\nUpdated daily temperatures:");
        printTemperatures(temperatures);
    }

    // Method to print all temperatures
    public static void printTemperatures(int[] temperatures) {
        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", 
                         "Friday","Saturday", "Sunday"};
        for (int i = 0; i < temperatures.length; i++) {
            System.out.println(days[i] + ": " + temperatures[i] + "°F");
        }
    }

    // Method to modify a temperature
    public static void modifyTemperature(int[] temperatures, int dayIndex, 
                                                               int newTemperature) {
        if (dayIndex >= 0 && dayIndex < temperatures.length) {
            temperatures[dayIndex] = newTemperature;
        } else {
            System.out.println("Invalid day index!");
        }
    }
}

輸出:

public class Main {
    public static void main(String[] args) {
        // Stores product quantities
        int[] quantities = new int[4];   
        // Storing product quantities
        quantities[0] = 50;  
        quantities[1] = 30;  
        quantities[2] = 20;  
        quantities[3] = 40;  
        // Prints the product quantities
        for (int i = 0; i < quantities.length; i++) {
            System.out.println("Product " + (i + 1) + " Quantity: " 
                                                            +   quantities[i]);
        }
    }
}

場景 3
數(shù)組可用於儲(chǔ)存和排序?qū)W生在特定班級的成績。

Product 1 Quantity: 50
Product 2 Quantity: 30
Product 3 Quantity: 20
Product 4 Quantity: 40

輸出

public class Main {
    public static void main(String[] args) {
        // Stores daily temperatures 
        int[] temperatures = {68, 70, 75, 72, 69, 71, 73};

        // Prints initial temperatures
        System.out.println("Initial daily temperatures:");
        printTemperatures(temperatures);

        // Modifies temperatures
        modifyTemperature(temperatures, 2, 78);
        modifyTemperature(temperatures, 5, 74);

        // Prints updated temperatures
        System.out.println("\nUpdated daily temperatures:");
        printTemperatures(temperatures);
    }

    // Method to print all temperatures
    public static void printTemperatures(int[] temperatures) {
        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", 
                         "Friday","Saturday", "Sunday"};
        for (int i = 0; i < temperatures.length; i++) {
            System.out.println(days[i] + ": " + temperatures[i] + "°F");
        }
    }

    // Method to modify a temperature
    public static void modifyTemperature(int[] temperatures, int dayIndex, 
                                                               int newTemperature) {
        if (dayIndex >= 0 && dayIndex < temperatures.length) {
            temperatures[dayIndex] = newTemperature;
        } else {
            System.out.println("Invalid day index!");
        }
    }
}

總而言之,Java 陣列具有固定大小,它們儲(chǔ)存相同類型的多個(gè)值。它們透過使用索引提供對元素的高效、持續(xù)的訪問,使它們適合需要關(guān)注記憶體開銷和速度的場景。雖然陣列不提供像 ArrayList 這樣的集合的靈活性,但它們?nèi)匀皇?Java 有效處理有序資料工具包中非常寶貴的一部分。


參考文獻(xiàn):

Oracle 文件。 (日期不詳)。 集合 (Java SE 21) [Java 平臺,標(biāo)準(zhǔn)版 Java API 規(guī)格]。甲骨文。取自 https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Collection.html/

教程點(diǎn)。 (日期不詳)。 Java 介面。教程點(diǎn)。取自 https://www.tutorialspoint.com/java/java_interfaces.htm


原刊於 Alex.omegapy on Medium,由 Level UP Coding 於 2024 年 10 月 16 日發(fā)布。

以上是Java 中的陣列:特徵、用法和實(shí)際場景的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

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

hashmap和hashtable之間的區(qū)別? hashmap和hashtable之間的區(qū)別? Jun 24, 2025 pm 09:41 PM

HashMap與Hashtable的區(qū)別主要體現(xiàn)在線程安全、null值支持及性能方面。 1.線程安全方面,Hashtable是線程安全的,其方法大多為同步方法,而HashMap不做同步處理,非線程安全;2.null值支持上,HashMap允許一個(gè)null鍵和多個(gè)null值,Hashtable則不允許null鍵或值,否則拋出NullPointerException;3.性能方面,HashMap因無同步機(jī)制效率更高,Hashtable因每次操作加鎖性能較低,推薦使用ConcurrentHashMap替

為什麼我們需要包裝紙課? 為什麼我們需要包裝紙課? Jun 28, 2025 am 01:01 AM

Java使用包裝類是因?yàn)榛緮?shù)據(jù)類型無法直接參與面向?qū)ο癫僮?,而?shí)際需求中常需對象形式;1.集合類只能存儲(chǔ)對象,如List利用自動(dòng)裝箱存儲(chǔ)數(shù)值;2.泛型不支持基本類型,必須使用包裝類作為類型參數(shù);3.包裝類可表示null值,用於區(qū)分未設(shè)置或缺失的數(shù)據(jù);4.包裝類提供字符串轉(zhuǎn)換等實(shí)用方法,便於數(shù)據(jù)解析與處理,因此在需要這些特性的場景下,包裝類不可或缺。

什麼是接口中的靜態(tài)方法? 什麼是接口中的靜態(tài)方法? Jun 24, 2025 pm 10:57 PM

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

JIT編譯器如何優(yōu)化代碼? JIT編譯器如何優(yōu)化代碼? Jun 24, 2025 pm 10:45 PM

JIT編譯器通過方法內(nèi)聯(lián)、熱點(diǎn)檢測與編譯、類型推測與去虛擬化、冗餘操作消除四種方式優(yōu)化代碼。 1.方法內(nèi)聯(lián)減少調(diào)用開銷,將頻繁調(diào)用的小方法直接插入調(diào)用處;2.熱點(diǎn)檢測識別高頻執(zhí)行代碼並集中優(yōu)化,節(jié)省資源;3.類型推測收集運(yùn)行時(shí)類型信息實(shí)現(xiàn)去虛擬化調(diào)用,提升效率;4.冗餘操作消除根據(jù)運(yùn)行數(shù)據(jù)刪除無用計(jì)算和檢查,增強(qiáng)性能。

什麼是實(shí)例初始器塊? 什麼是實(shí)例初始器塊? Jun 25, 2025 pm 12:21 PM

實(shí)例初始化塊在Java中用於在創(chuàng)建對象時(shí)運(yùn)行初始化邏輯,其執(zhí)行先於構(gòu)造函數(shù)。它適用於多個(gè)構(gòu)造函數(shù)共享初始化代碼、複雜字段初始化或匿名類初始化場景,與靜態(tài)初始化塊不同的是它每次實(shí)例化時(shí)都會(huì)執(zhí)行,而靜態(tài)初始化塊僅在類加載時(shí)運(yùn)行一次。

什麼是類型鑄造? 什麼是類型鑄造? Jun 24, 2025 pm 11:09 PM

類型轉(zhuǎn)換有兩種:隱式和顯式。 1.隱式轉(zhuǎn)換自動(dòng)發(fā)生,如將int轉(zhuǎn)為double;2.顯式轉(zhuǎn)換需手動(dòng)操作,如使用(int)myDouble。需要類型轉(zhuǎn)換的情況包括處理用戶輸入、數(shù)學(xué)運(yùn)算或函數(shù)間傳遞不同類型的值時(shí)。需要注意的問題有:浮點(diǎn)數(shù)轉(zhuǎn)整數(shù)會(huì)截?cái)嘈?shù)部分、大類型轉(zhuǎn)小類型可能導(dǎo)致數(shù)據(jù)丟失、某些語言不允許直接轉(zhuǎn)換特定類型。正確理解語言的轉(zhuǎn)換規(guī)則有助於避免錯(cuò)誤。

變量的最終關(guān)鍵字是什麼? 變量的最終關(guān)鍵字是什麼? Jun 24, 2025 pm 07:29 PM

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

什麼是工廠模式? 什麼是工廠模式? Jun 24, 2025 pm 11:29 PM

工廠模式用於封裝對象創(chuàng)建邏輯,使代碼更靈活、易維護(hù)、松耦合。其核心答案是:通過集中管理對象創(chuàng)建邏輯,隱藏實(shí)現(xiàn)細(xì)節(jié),支持多種相關(guān)對象的創(chuàng)建。具體描述如下:工廠模式將對象創(chuàng)建交給專門的工廠類或方法處理,避免直接使用newClass();適用於多類型相關(guān)對象創(chuàng)建、創(chuàng)建邏輯可能變化、需隱藏實(shí)現(xiàn)細(xì)節(jié)的場景;例如支付處理器中通過工廠統(tǒng)一創(chuàng)建Stripe、PayPal等實(shí)例;其實(shí)現(xiàn)包括工廠類根據(jù)輸入?yún)?shù)決定返回的對象,所有對象實(shí)現(xiàn)共同接口;常見變體有簡單工廠、工廠方法和抽象工廠,分別適用於不同複雜度的需求。

See all articles