第十二次
构造器 java.util.Vecor
1. Vector(int) 给数组初始化
方法有:indexOf(Object,int):int 寻找在字符串中的位置
firstElement():E 最前一个元素
lastElement():E 最后一个元素
remove(int):E 按下标移除返回值
remove(Object) 按下标移除返回boolean类型
clear():void 对象全部清除
addAll(Collection):boolean 批量加入
removeAll 批量移除
removeAllElements() 把集合里的所有对象全部清除
subList(int,int) 从指定位置截取
subList(int,int) 截取
Iterator():Iterator E 迭代取值
注 E:泛型
泛型是用来控制类型的。
2.java.util.Vector
public class Vector {
privateObject[] objs = null;
publicint size() { return count; }
privateint count=0;
publicvoid add(Object obj) {
if (objs == null) {
objs= new Object[6];
objs[0]= obj;
count++;
} else {
if(count>=objs.length){
Object[] objs1 = newObject[(int)(objs.length *1.5F)];
System.arraycopy(objs, 0, objs1, 0, objs.length);
objs = objs1;
}
objs[count]= obj;
count++;
}
}
publicObject get(int index) {
return objs[index];
}
}
import java.util.*;
import java.util.Vector;
public class Test {
staticclass Dog {//定义内部类Dog
private String name;
public Dog(String name) { this.name = name; }
public String toString() { return name; }
}
publicstatic void main(String[] args) {
java.util.Vector
v.add("aaa1");
v.add("aaa2");
v.add("aaa3");
for (int i = 0; i < v.size(); i++) {
System.out.println(v.get(i));
}//方法一:使用get()方法输出
java.util.Vector
v1.add("aaa4");
v1.add("aaa5");
v1.add("aaa6");
for (String i:v1) {
System.out.println(i);
}//方法二:直接输出
java.util.Vector
list.add("bbb1");
list.add("bbb2");
list.add("bbb3");
java.util.Iterator
while(it.hasNext()){//hasNext()摇动水轮
System.out.println(it.next());//next()拿到掉下来的对象
}//方法三:使用迭代器里的方法
java.util.Vector
list1.add(new Dog("旺财1"));
list1.add(new Dog("旺财2"));
list1.add(new Dog("旺财3"));
java.util.Iterator
while (it1.hasNext()) {
Dogd=(Dog)it1.next();
System.out.println(d.name);
}
while(it1.hasNext()){
System.out.println(it1.next());
}
}
}
二、枚举
方式一:
public class Exe1 {
privatestatic String name="李四";//定义四个变量并初始化
privatestatic String address="陕西";
privatestatic String sex="男";
privatestatic String phone="123456";
publicstatic final int NAME=1;//定义四个常量
publicstatic final int ADDRESS=2;
publicstatic final int SEX=3;
publicstatic final int PHONE=4;
publicstatic void print(int i){
if(i==1){
System.out.println(name);
}else if(i==2){
System.out.println(address);
}else if(i==3){
System.out.println(sex);
}else
System.out.println(phone);
}
publicstatic void main(String[] args) {
print(3);
}
}
方式二:使用枚举方法
public enum Stu {
NAME,SEX,ADDRESS,PHONE;
}
public class Exe2 {
private static String name="李四";
privatestatic String address="陕西";
privatestatic String sex="男";
privatestatic String phone="123456";
publicstatic void print(Stu i){
if(i==Stu.NAME){
System.out.println(name);
}else if(i==Stu.ADDRESS){
System.out.println(address);
}else if(i==Stu.SEX){
System.out.println(sex);
}else
System.out.println(phone);
}
publicstatic void main(String[] args) {
print(Stu.ADDRESS);
}
}