每日要點
容器
容器(集合框架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();