Java學習筆記 - 第017天

每日要點

容器

容器(集合框架Container) - 承載其他對象的對象

Collection

  • List
  • ArrayList
  • LinkedList
  • Set

List

ArrayList - 底層實現(xiàn)是一個數(shù)組 使用連續(xù)內(nèi)存 可以實現(xiàn)隨機存取
List<String> list = new ArrayList<>();
LinkedList - 底層實現(xiàn)是一個雙向循環(huán)鏈表 可以使用碎片內(nèi)存 不能隨機存取 但是增刪元素是需要修改引用即可 所以增刪元素時有更好的性能
List<String> list = new LinkedList<>();
從Java 5開始容器可以指定泛型參數(shù)來限定容器中對象引用的類型
帶泛型參數(shù)的容器比不帶泛型參數(shù)的容器中使用上更加方便
Java 7開始構(gòu)造器后面的泛型參數(shù)可以省略 - 鉆石語法

List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();

Java 5
容器中只能放對象的引用不能放基本數(shù)據(jù)類型
所以向容器中添加基本數(shù)據(jù)類型時會自動裝箱(auto-boxing)
所謂自動裝箱就是將基本數(shù)據(jù)類型處理成對應(yīng)的包裝類型

list.add(1000); // list.add(new Integer(1000));
list.add(3.14); // list.add(new Double(3.14));
list.add(true); // list.add(new Boolean(true));

List接口普通方法:


  • list.add("apple");
    根據(jù)索引添加對象:
    list.add(list.size(), "shit");

  • list.remove("apple");
    清空:
    list.clear();
    根據(jù)指定的參考系刪除所有
    list.removeAll(temp);
    根據(jù)指定的參考系保留所有
    list.retainAll(temp);
  • 方法一:
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
  • 方法二:
        for (Object object : list) {
            System.out.println(object.getClass());
        }
  • 方法三:
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

Java 8以后新特性
從Java 8開始可以給容器發(fā)送forEach消息對元素進行操作
orEach方法的參數(shù)可以是方法引用也可以是Lambda表達式
方法引用
list.forEach(System.out::println);
Lambda表達式

        list.forEach(e -> {
            System.out.println(e.toUpperCase());
        });

雜項

基本類型  包裝類型(Wrapper class)
byte      Byte ---> new Byte(1)
short     Short
int      Integer
long      Long
float      Float
double    Double
boolean   Boolean

例子

  • 1.自動裝箱和自動拆箱
        Object object1 = 100; // 自動裝箱
        System.out.println(object1.getClass());
        Integer object2 = (Integer) object1;
        int a = object2;  // 自動拆箱
        int b = (Integer) object1;
        System.out.println(a);
        System.out.println(b);
        
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            // 自動裝箱(auto-boxing) int ---> Integer
            list.add((int) (Math.random() * 20));
        }
        for (Integer x : list) {   // int x : list
            // 自動拆箱(auto-unboxing) Integer對象 ---> int
            if (x > 10) {
                System.out.println(x);
            }
        }
  • 2.面試題: Integer c = 123; Integer d = 123; 是否相等
        int[] x = {1, 2, 3};
        int[] y = {1, 2, 3};
        System.out.println(x.hashCode());
        System.out.println(y.hashCode());
        System.out.println(x == y);
        // 數(shù)組沒有重寫equals方法
        System.out.println(x.equals(y));
        System.out.println(Arrays.equals(x, y));
        
        Integer a = 12345;
        Integer b = 12345;
        
        System.out.println(a == b);
        System.out.println(a.equals(b));
        
        // Integer 有準備 -128~127的常量
        Integer c = 123;
        Integer d = 123;
        
        System.out.println(c == d);
        System.out.println(c.intValue() == d.intValue());
        System.out.println(c.equals(d));

貪吃蛇

方向枚舉:

public enum Direction {
    UP, RIGHT, DOWN, LEFT
}

蛇節(jié)點:

/**
 * 蛇節(jié)點
 * @author Kygo
 *
 */
public class SnakeNode {
    private int x;
    private int y;
    private int size;
    
    public SnakeNode(int x, int y, int size) {
        this.x = x;
        this.y = y;
        this.size = size;
    }
    
    public void draw(Graphics g) {
        g.fillRect(x, y, size, size);
        Color currentColor = g.getColor();
        g.setColor(Color.BLACK);
        g.drawRect(x, y, size, size);
        g.setColor(currentColor);
    }
    
    public int getX() {
        return x;
    }
    
    public int getY() {
        return y;
    }
    
    public int getSize() {
        return size;
    }
    
    public void setX(int x) {
        this.x = x;
    }
    
    public void setY(int y) {
        this.y = y;
    }
}

蛇類:

public class Snake {
    private List<SnakeNode> nodes;
    private Color color;
    private Direction dir;
    private Direction newDir;
    
    public Snake() {
        this(Color.GREEN);
    }
    
    public Snake(Color color) {
        this.color = color;
        this.dir = Direction.LEFT;
        this.nodes = new LinkedList<>();
        for (int i = 0; i < 5; i++) {
            SnakeNode node = new SnakeNode(300 + i * 20, 300, 20);
            nodes.add(node);
        }
    }
    
    public void move() {
        if (newDir != null) {
            dir = newDir;
            newDir = null;
        }
        SnakeNode head = nodes.get(0);
        int x = head.getX();
        int y = head.getY();
        int size = head.getSize();
        switch (dir) {
        case UP:
            y -= size;
            break;
        case RIGHT:
            x += size;
            break;
        case DOWN:
            y += size;
            break;
        case LEFT:
            x -= size;
            break;
        }
        SnakeNode newHead = new SnakeNode(x, y, size);
        nodes.add(0, newHead);
        nodes.remove(nodes.size() - 1);
    }
    
    public boolean eatEgg(SnakeNode egg) {
        if (egg.getX() == nodes.get(0).getX() && egg.getY() == nodes.get(0).getY()) {
            nodes.add(egg);
            return true;
        }
        return false;
    }
    
    public boolean die() {
        for (int i = 1; i < nodes.size(); i++) {
            if (nodes.get(0).getX() == nodes.get(i).getX() && nodes.get(0).getY() == nodes.get(i).getY()) {
                return true;
            }
        }
        return false;
    }
    
    public void draw(Graphics g) {
        g.setColor(color);
        for (SnakeNode snakeNode : nodes) {
            snakeNode.draw(g);
        }
    }
    
    public Direction getDir() {
        return dir;
    }
    
    public void setDir(Direction newDir) {
        if ((this.dir.ordinal() + newDir.ordinal()) % 2 != 0) {
            if (this.newDir == null) {
                this.newDir = newDir;   
            }       
        }
    }
}

貪吃蛇窗口:

public class SnakeGameFrame extends JFrame {
    private BufferedImage image = new BufferedImage(600, 600, 1);
    private Snake snake = new Snake();
    private SnakeNode egg = new SnakeNode(60, 60, 20);

    public SnakeGameFrame() {
        this.setTitle("貪吃蛇");
        this.setSize(600, 600);
        this.setResizable(false);
        this.setLocationRelativeTo(null);

        // 綁定窗口監(jiān)聽器
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                // Todo: 存檔
                System.exit(0);
            }
        });
        // 綁定鍵盤事件監(jiān)聽器
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                Direction newDir = null;
                switch (keyCode) {
                case KeyEvent.VK_W:
                    newDir = Direction.UP;
                    break;
                case KeyEvent.VK_D:
                    newDir = Direction.RIGHT;
                    break;
                case KeyEvent.VK_S:
                    newDir = Direction.DOWN;
                    break;
                case KeyEvent.VK_A:
                    newDir = Direction.LEFT;
                    break;
                }
                if (newDir != null && newDir != snake.getDir()) {
                    snake.setDir(newDir);
                }
            }
        });

        Timer timer = new Timer(200, e -> {
            snake.move();
            if (snake.eatEgg(egg)) {
                int x = (int) (Math.random() * 31) * 20;
                int y = (int) (Math.random() * 30 + 1) * 20;
                egg.setX(x);
                egg.setY(y);
            }
            if (snake.die()) {
                System.out.println("死了");
            }
            repaint();
        });
        timer.start();
    }

    @Override
    public void paint(Graphics g) {
        Graphics otherGraphics = image.getGraphics();
        super.paint(otherGraphics);
        snake.draw(otherGraphics);
        egg.draw(otherGraphics);
        g.drawImage(image, 0, 0, null);
    }

    public static void main(String[] args) {
        new SnakeGameFrame().setVisible(true);
    }
}

作業(yè)

  • 2.設(shè)計電話薄
    聯(lián)系人
package com.kygo.book;
public class Contact {
    private String name;
    private String tel;
    
    public Contact(String name, String tel) {
        this.name = name;
        this.tel = tel;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }
    
    @Override
    public String toString() {
        return "姓名:" + name + "\n電話號碼:" + tel;
    }
}

通訊錄:

public class AddressBook {
    private List<Contact> list = new ArrayList<>();
    
    public Contact query(String name) {
        for (Contact contact : list) {
            if (contact.getName().equals(name)) {
                return contact;
            }
        }
        return null;
    }   
public List<Contact> queryAll() {
        return list;
    }
    public boolean add(Contact contact) {
        if (list.add(contact)) {
            return true;
        }
        return false;
    }
    
    public boolean remove(String name) {
        Contact contact = query(name);
        if (list.remove(contact)) {
            return true;
        }
        return false;
    }
    
    public boolean update(Contact contact, String name, String tel) {
        if (list.contains(contact)) {
            int index = list.indexOf(contact);
            list.get(index).setName(name);
            list.get(index).setTel(tel);
            return true;
        }
        else {
            return false;
        }
    }
}

測試:

        Scanner input = new Scanner(System.in);
        AddressBook addressBook = new AddressBook();
        boolean goOn = true;
        while (goOn) {
            System.out.println("歡迎使用通訊錄: \n請選擇你要使用的功能: \n" 
        + "1.查詢\n2.添加\n3.修改\n4.刪除\n5.查詢所有\(zhòng)n6.退出");
            int choose = input.nextInt();
            if (1 <= choose && choose <= 6) {
                switch (choose) {
                case 1:
                {
                    System.out.print("請輸入你要查詢聯(lián)系人的名字: ");
                    String name = input.next();
                    System.out.println(addressBook.query(name));
                    break;
                }
                case 2:
                {
                    System.out.print("請輸入聯(lián)系人名稱: ");
                    String name = input.next();
                    System.out.print("請輸入聯(lián)系人電話: ");
                    String tel = input.next();
                    Contact contact = new Contact(name, tel);
                    if (addressBook.add(contact)) {
                        System.out.println("添加聯(lián)系人成功!");
                    }
                    else {
                        System.out.println("添加聯(lián)系人失敗");
                    }
                    break;
                }
                case 3:
                {
                    System.out.print("請輸入你要修改的聯(lián)系人姓名: ");
                    String name = input.next();
                    if (addressBook.query(name) != null) {
                        System.out.print("請輸入新名字: ");
                        String newName = input.next();
                        System.out.print("請輸入新電話: ");
                        String newTel = input.next();
                        Contact contact = addressBook.query(name);
                        if (addressBook.update(contact, newName, newTel)) {
                            System.out.println("修改聯(lián)系人成功!");
                        } else {
                            System.out.println("修改聯(lián)系人失敗");
                        } 
                    }
                    else {
                        System.out.println("沒有這個聯(lián)系人!");
                    }
                    break;
                }
                case 4:
                {
                    System.out.print("請輸入你要刪除聯(lián)系人的名字: ");
                    String name = input.next();
                    if (addressBook.remove(name)) {
                        System.out.println("刪除聯(lián)系人成功!");
                    }
                    else {
                        System.out.println("刪除聯(lián)系人失敗");
                    }
                    break;
                }
                case 5:
                {
                    List<Contact> list = addressBook.queryAll();
                    for (Contact contact : list) {
                        System.out.println(contact);
                    }
                }
                case 6:
                    goOn = false;
                    break;
                }
            }
        }
        input.close();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子航闺,更是在濱河造成了極大的恐慌,老刑警劉巖砌溺,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異变隔,居然都是意外死亡规伐,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進店門匣缘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來猖闪,“玉大人,你說我怎么就攤上這事肌厨∨嗷牛” “怎么了?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵柑爸,是天一觀的道長吵护。 經(jīng)常有香客問我,道長表鳍,這世上最難降的妖魔是什么馅而? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮进胯,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘原押。我一直安慰自己胁镐,他們只是感情好,可當我...
    茶點故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著盯漂,像睡著了一般颇玷。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上就缆,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天帖渠,我揣著相機與錄音,去河邊找鬼竭宰。 笑死空郊,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的切揭。 我是一名探鬼主播狞甚,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼廓旬!你這毒婦竟也來了哼审?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤孕豹,失蹤者是張志新(化名)和其女友劉穎涩盾,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體励背,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡春霍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了椅野。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片终畅。...
    茶點故事閱讀 40,444評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖竟闪,靈堂內(nèi)的尸體忽然破棺而出离福,到底是詐尸還是另有隱情,我是刑警寧澤炼蛤,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布妖爷,位于F島的核電站,受9級特大地震影響理朋,放射性物質(zhì)發(fā)生泄漏絮识。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一嗽上、第九天 我趴在偏房一處隱蔽的房頂上張望次舌。 院中可真熱鬧,春花似錦兽愤、人聲如沸彼念。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽逐沙。三九已至哲思,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間吩案,已是汗流浹背棚赔。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留徘郭,地道東北人靠益。 一個月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像崎岂,于是被迫代替她去往敵國和親捆毫。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法冲甘,類相關(guān)的語法绩卤,內(nèi)部類的語法,繼承相關(guān)的語法江醇,異常的語法濒憋,線程的語...
    子非魚_t_閱讀 31,661評論 18 399
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)陶夜,斷路器凛驮,智...
    卡卡羅2017閱讀 134,696評論 18 139
  • 多態(tài) 任何域的訪問操作都將有編譯器解析,如果某個方法是靜態(tài)的条辟,它的行為就不具有多態(tài)性 java默認對象的銷毀順序與...
    yueyue_projects閱讀 946評論 0 1
  • 一黔夭、 1、請用Java寫一個冒泡排序方法 【參考答案】 public static void Bubble(int...
    獨云閱讀 1,380評論 0 6