标签:private code 程序 print blog log contract ica ima
数组列表
在java.util包中有一个类可以实现数组所有的功能,而且没有数组的大小限制,它就是ArrayList。
数组列表是一个存储同一类对象或具有共同超类的对象的数据结构。在程序运行时,列表可以根据需要调整大小。
创建数组列表是最简单的方法是调用其不带参数的构造函数。
ArrayList servants = new ArrayList();
在创建数组列表时,可以指定一个初始的容量(大小),这为列表能存放多少个元素提供了指导。该容量作为一个整型参数传递给构造函数
ArrayList servants = new ArrayList(30);
ArrayList<String> servants = new ArrayList<String>();
1 import java.awt.*; 2 import java.util.*; 3 4 5 public class Battlepoint { 6 ArrayList<Point> targets = new ArrayList<Point>(); 7 8 public Battlepoint() { 9 //create targets to shoot at 10 createTargets(); 11 //display the game map 12 showMap(); 13 //shoot at three points 14 shoot(7, 4); 15 shoot(3, 3); 16 shoot(9, 2); 17 //display the map again 18 showMap(); 19 } 20 21 private void showMap() { 22 System.out.println("\n 1 2 3 4 5 6 7 8 9"); 23 for (int column = 1; column < 10; column++) { 24 for (int row = 1; row < 10; row++) { 25 if (row == 1) { 26 System.out.print(column + " "); 27 } 28 System.out.print(" "); 29 Point cell = new Point(row, column); 30 if (targets.indexOf(cell) > -1) { 31 //a target is at this position 32 System.out.print("X"); 33 } else { 34 //no target is here 35 System.out.print("."); 36 } 37 System.out.print(" "); 38 } 39 System.out.println(); 40 } 41 System.out.println(); 42 } 43 44 private void createTargets() { 45 Point p1 = new Point(5, 9); 46 targets.add(p1); 47 Point p2 = new Point(4, 5); 48 targets.add(p2); 49 Point p3 = new Point(9, 2); 50 targets.add(p3); 51 } 52 53 private void shoot(int x, int y) { 54 Point shot = new Point(x, y); 55 System.out.print("Firing at (" + x + "," + y + ")..."); 56 if (targets.indexOf(shot) > -1) { 57 System.out.println("you sank my battlepoint!"); 58 targets.remove(shot); 59 } else { 60 System.out.println("miss."); 61 } 62 } 63 64 public static void main(String[] arguments) { 65 new Battlepoint(); 66 } 67 }
标签:private code 程序 print blog log contract ica ima
原文地址:http://www.cnblogs.com/dulixiaoqiao/p/6517024.html