刚刚开始学习java, 路上的拦路虎还真不少。
在Java的vector中存储了一种用户自定义的数据类型,非基本数据类型,如何要删除,如何删除呢?这其中就牵扯到对象比较的问题。理解这个问题,其实用C++的指针来理解可能更好理解一些。
另外要重载用户自定义类型的 boolean equals(Object obj)这个方法,才能正确应用vector中相关和对象比较的方法。
package com.container; public class student { private int code_; private String name_; private int grade_; public student(int code, String name, int grade) { code_ = code; name_ = name; grade_ = grade; } public student(student stu) { code_ = stu.getcode(); name_ = stu.getname(); grade_ = stu.getgrade(); } public void output() { System.out.println("code=" + code_ + " name=" + name_ + " grade=" + grade_); } public int getcode() { return code_; } public String getname() { return name_; } public int getgrade() { return grade_; } public void setcode(int code) { code_ = code; } public void setname(String name) { name_ = name; } public void setgrade(int grade) { grade_ = grade; } public boolean equals(Object obj){ student stu = (student)obj; if (code_ == stu.code_ && name_.equals(stu.name_) && grade_ == stu.grade_) { return true; } return false; } }
package com.container; import java.util.Vector; public class studentlist { Vector list = new Vector(10, 5); public studentlist() { list.clear(); } public void add(student stu) { list.add(stu); } public void add(student stu, int index) { list.add(index, stu); } public boolean delete(student stu) { return list.remove(stu); } public boolean select(student stu) { if (list.indexOf(stu) == -1) { return false; } return true; } public void output() { for (int i = 0; i < list.size(); i++) { ((student) list.get(i)).output(); } } }
package com.softel; import com.container.*; public class test { public static void main(String[] args) { studentlist list = new studentlist(); for (int i = 0; i < 5; i++) { student stu = new student(i, "wangxu" + i, i); list.add(stu); } student stu = new student(0, "wangxu0", 0); if (list.select(stu)) { System.out.println("true"); } else { System.out.println("false"); } list.delete(stu); if (list.select(stu)) { System.out.println("true"); } else { System.out.println("false"); } list.output(); } }