Java學(xué)習(xí)筆記 - 第017天

每日要點(diǎn)

容器

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

Collection

  • List
  • ArrayList
  • LinkedList
  • Set

List

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

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

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

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ù)索引添加對(duì)象:
    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開(kāi)始可以給容器發(fā)送forEach消息對(duì)元素進(jìn)行操作
orEach方法的參數(shù)可以是方法引用也可以是Lambda表達(dá)式
方法引用
list.forEach(System.out::println);
Lambda表達(dá)式

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

雜項(xiàng)

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

例子

  • 1.自動(dòng)裝箱和自動(dòng)拆箱
        Object object1 = 100; // 自動(dòng)裝箱
        System.out.println(object1.getClass());
        Integer object2 = (Integer) object1;
        int a = object2;  // 自動(dòng)拆箱
        int b = (Integer) object1;
        System.out.println(a);
        System.out.println(b);
        
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            // 自動(dòng)裝箱(auto-boxing) int ---> Integer
            list.add((int) (Math.random() * 20));
        }
        for (Integer x : list) {   // int x : list
            // 自動(dòng)拆箱(auto-unboxing) Integer對(duì)象 ---> 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ù)組沒(méi)有重寫(xiě)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 有準(zhǔn)備 -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é)點(diǎn):

/**
 * 蛇節(jié)點(diǎn)
 * @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;
    }
}

蛇類(lèi):

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)聽(tīng)器
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                // Todo: 存檔
                System.exit(0);
            }
        });
        // 綁定鍵盤(pán)事件監(jiān)聽(tīng)器
        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è)計(jì)電話(huà)薄
    聯(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電話(huà)號(hào)碼:" + 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;
        }
    }
}

測(cè)試:

        Scanner input = new Scanner(System.in);
        AddressBook addressBook = new AddressBook();
        boolean goOn = true;
        while (goOn) {
            System.out.println("歡迎使用通訊錄: \n請(qǐng)選擇你要使用的功能: \n" 
        + "1.查詢(xún)\n2.添加\n3.修改\n4.刪除\n5.查詢(xún)所有\(zhòng)n6.退出");
            int choose = input.nextInt();
            if (1 <= choose && choose <= 6) {
                switch (choose) {
                case 1:
                {
                    System.out.print("請(qǐng)輸入你要查詢(xún)聯(lián)系人的名字: ");
                    String name = input.next();
                    System.out.println(addressBook.query(name));
                    break;
                }
                case 2:
                {
                    System.out.print("請(qǐng)輸入聯(lián)系人名稱(chēng): ");
                    String name = input.next();
                    System.out.print("請(qǐng)輸入聯(lián)系人電話(huà): ");
                    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("請(qǐng)輸入你要修改的聯(lián)系人姓名: ");
                    String name = input.next();
                    if (addressBook.query(name) != null) {
                        System.out.print("請(qǐng)輸入新名字: ");
                        String newName = input.next();
                        System.out.print("請(qǐng)輸入新電話(huà): ");
                        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("沒(méi)有這個(gè)聯(lián)系人!");
                    }
                    break;
                }
                case 4:
                {
                    System.out.print("請(qǐng)輸入你要?jiǎng)h除聯(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)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類(lèi)相關(guān)的語(yǔ)法,內(nèi)部類(lèi)的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 31,778評(píng)論 18 399
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,991評(píng)論 19 139
  • 多態(tài) 任何域的訪問(wèn)操作都將有編譯器解析,如果某個(gè)方法是靜態(tài)的,它的行為就不具有多態(tài)性 java默認(rèn)對(duì)象的銷(xiāo)毀順序與...
    yueyue_projects閱讀 994評(píng)論 0 1
  • 一、 1、請(qǐng)用Java寫(xiě)一個(gè)冒泡排序方法 【參考答案】 public static void Bubble(int...
    獨(dú)云閱讀 1,421評(píng)論 0 6
  • 圓滾滾的喵閱讀 260評(píng)論 2 1