每日要点
容器
容器(集合框架Container) - 承载其他对象的对象
Collection
- List
- ArrayList
- LinkedList
- Set
List
ArrayList - 底层实现是一个数组 使用连续内存 可以实现随机存取
List<String> list = new ArrayList<>();
LinkedList - 底层实现是一个双向循环链表 可以使用碎片内存 不能随机存取 但是增删元素是需要修改引用即可 所以增删元素时有更好的性能
List<String> list = new LinkedList<>();
从Java 5开始容器可以指定泛型参数来限定容器中对象引用的类型
带泛型参数的容器比不带泛型参数的容器中使用上更加方便
Java 7开始构造器后面的泛型参数可以省略 - 钻石语法
List<String> list = new ArrayList<String>();
List<String> list = new ArrayList<>();
Java 5
容器中只能放对象的引用不能放基本数据类型
所以向容器中添加基本数据类型时会自动装箱(auto-boxing)
所谓自动装箱就是将基本数据类型处理成对应的包装类型
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");
根据索引添加对象:
list.add(list.size(), "shit");
- 删
list.remove("apple");
清空:
list.clear();
根据指定的参考系删除所有
list.removeAll(temp);
根据指定的参考系保留所有
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开始可以给容器发送forEach消息对元素进行操作
orEach方法的参数可以是方法引用也可以是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);
// 数组没有重写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
}
蛇节点:
/**
* 蛇节点
* @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);
// 绑定窗口监听器
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// Todo: 存档
System.exit(0);
}
});
// 绑定键盘事件监听器
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);
}
}
作业
-
2.设计电话薄
联系人
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.查询所有\n6.退出");
int choose = input.nextInt();
if (1 <= choose && choose <= 6) {
switch (choose) {
case 1:
{
System.out.print("请输入你要查询联系人的名字: ");
String name = input.next();
System.out.println(addressBook.query(name));
break;
}
case 2:
{
System.out.print("请输入联系人名称: ");
String name = input.next();
System.out.print("请输入联系人电话: ");
String tel = input.next();
Contact contact = new Contact(name, tel);
if (addressBook.add(contact)) {
System.out.println("添加联系人成功!");
}
else {
System.out.println("添加联系人失败");
}
break;
}
case 3:
{
System.out.print("请输入你要修改的联系人姓名: ");
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("修改联系人成功!");
} else {
System.out.println("修改联系人失败");
}
}
else {
System.out.println("没有这个联系人!");
}
break;
}
case 4:
{
System.out.print("请输入你要删除联系人的名字: ");
String name = input.next();
if (addressBook.remove(name)) {
System.out.println("删除联系人成功!");
}
else {
System.out.println("删除联系人失败");
}
break;
}
case 5:
{
List<Contact> list = addressBook.queryAll();
for (Contact contact : list) {
System.out.println(contact);
}
}
case 6:
goOn = false;
break;
}
}
}
input.close();