首先创建集合
先让指针走到最后面
然后让指针从后面往前走
判断是否到指定的元素
插入到指定元素前面
代码:
自定义类
package kehouzuoye19_2;
public class Worker {
private String name;
private int age;
private double salary;
public Worker() {
super();
}
public Worker(String name, int age, double salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void work() {
System.out.println(this.getName() + "正在工作");
}
@Override
public String toString() {
return "Worker [name=" + name + ", age=" + age + ", salary=" + salary
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
Worker w = (Worker)obj;
return this.name.equals (w.name) && this.age == w.age && this.salary == w.salary;
}
}
测试类:
package kehouzuoye19_2;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class WorkerDemo {
public static void main(String[] args) {
List list = new ArrayList();
Worker w1 = new Worker("凤姐", 18, 20000);
Worker w2 = new Worker("欧阳峰", 60, 8000);
Worker w3 = new Worker("刘德华", 40, 30000);
list.add(w1);
list.add(w2);
list.add(w3);
ListIterator lit = list.listIterator();
// while (lit.hasNext()) {
// //Worker w = (Worker) lit.next();
// System.out.println(lit.next());
// }
//(4)在"欧阳峰"之前插入一个员工,信息为:姓名:"张柏芝",年龄:35,工资3300
while (lit.hasNext()) {
System.out.println(lit.next());
}
while (lit.hasPrevious()){
//Object object = (Object) lit.next();
//Worker w = (Worker) lit.previous();
if (w2.equals(lit.previous())) {
lit.add( new Worker("张柏芝", 35, 3300));
// /*int i = lit.previousIndex();
// list.get(i);*/
System.out.println(lit.previous());
//
}
//}
// for (int i = 0; i < list.size(); i++) {
// System.out.println(list.get(i));
// }
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
|
|