Java學習筆記5(類的入門以及ArrayList)

來源:互聯網
上載者:User

標籤:move   結果   for   技術   顏色   聽音樂   添加   ble   out   

1.類的概念:將現實生活中的事物抽象成了代碼(類),我們可以使用自訂的數群組類型(類)來描述現實生活中的事物。

2.分析:用一部手機來分析,手機可以打電話,上網,聽音樂,這些就是方法,手機有型號,顏色,大小,這些就是屬性。

舉例:

寫一個手機類,

public class Phone{    String color;    String brand;    double size;} 

寫一個測試類別,和手機類在一個檔案夾下,

public class TestPhone{    public static void main(String[] args){        Phone p = new Phone();        p.color = "whilte";        p.brand = "vivo";        p.size = 5.0;        System.out.println(p.color+"        "+p.brand+"        "+p.size+"寸");    }}

運行結果:

 

記憶體分析:

1.TestPhone.class進入方法區,只有一個main方法

2.Phone.class進入方法區,有三個屬性

3.main方法進入棧中運行

4.在new Phone時候,JVM在堆中開闢記憶體空間,用來儲存Phone對象,並獲得地址

5.類中的三個屬性,跟隨容器進入到堆記憶體,並賦予預設值(null,null,0.0)

6.p指向這個記憶體位址

7.p.color等是記憶體空間中找到color屬性,並賦值

 

ArrayList簡單介紹:

集合,不限長度。儲存的是參考型別,不儲存基本類型,如int,double不能寫,要改成相應的參考型別。

建立(Phone是之前寫的一個類):

import java.util.ArrayList;public class ArrayListDemo{    public static void main(String[] args){        ArrayList<String> array = new ArrayList<String>();        ArrayList<Integer> array2 = new ArrayList<Integer>();        ArrayList<Phone> array3 = new ArrayList<Phone>();    }}

方法:

import java.util.ArrayList;public class ArrayListDemo{    public static void main(String[] args){        ArrayList<String> array = new ArrayList<String>();        array.add("c++");//添加元素        array.add("python");        array.add("java");        array.add("php");        int size = array.size();//集合的大小        System.out.println(size);//4        String s = array.get(1);//擷取元素        System.out.println(s);//python                //遍曆        for(int i = 0 ; i < array.size(); i++){            System.out.println(array.get(i));        }                //其他方法        ArrayList<Integer> array2 = new ArrayList<Integer>();        array2.add(1);        array2.add(2);        array2.add(3);        array2.add(4);        array2.add(2,7);//在2的索引上加7        array2.set(0,10);//0索引設定為10        array2.remove(4);//刪除        for(int j = 0 ; j < array2.size(); j++){            System.out.println(array2.get(j));        }        //10,2,7,3        array2.clear();        //清除集合中的元素,容器還在    }}

 

Java學習筆記5(類的入門以及ArrayList)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.