program 5 Object 类链表、接口
概述
《第一行代码 JAVA》的 4.9 综合练习:宠物商店 中,利用接口技术和改进的链表(可以接收任何对象)实现了一个宠物商店的信息整理——具体而言包括 ①保存宠物的信息;②宠物上架、下架;③模糊查询。
仿造这个案例,本文试着重新写一个可以接收任何类、功能完善的Link,利用接口实现一个学校中各类人员的信息记录,并且能够实现查找、新增、删除、修改等一系列操作。
实现的程序如下:
1. Object 类链表
package wyh20200228;
/**
* 一个完整的链表,可以接收任何类型数据。
* 功能包括:增加、查询、取出、修改、删除、
* 元素个数、是否为空、输出、清空
* @author Yuan_hang
* @Date 2020年2月28日
*
*/
public class Link { //外部仅能看到这个类
// 内部类 - 节点
private class Node{
private Object obj;
private Node next;
public Node(Object obj){
this.obj = obj;
}
}
//*******************************
// 属性
private int linkLength;
private Node root;
//方法
/**
* 增加一个对象
* @param obj
*/
public void add(Object obj){
if(this.isEmpty()){
this.root = new Node(obj);
}
else{
Node temp = this.root;
while(temp.next != null){
temp = temp.next;
}
temp.next = new Node(obj);
}
}
/**
* 删除该对象
* @param obj
*/
public void delect(Object obj){
if(!this.isEmpty()){
Node temp = this.root;
while(temp.next != null){
if(temp.next.obj.equals(obj)){
temp.next = temp.next.next;
}else{temp = temp.next;}
}
if(this.root.obj.equals(obj)){
this.root = this.root.next;
}
}
}
/**
* 模糊查找并返回符合条件的第一个对象
* @param str
* @return
*/
public Object get(String str){
Object getObj = null;
Node temp = this.root;
if(!this.isEmpty()){
while(this.root != null && temp != null){
if(temp.obj.toString().contains(str)){
getObj = temp.obj;
temp = null;
}
if(temp != null){temp = temp.next;}
}
}
return getObj;
}
/**
* 根据字符串模糊查找
* @param str
*/
public void search(String str){
Node