问题引入
如图所示,是电商项目中商品分类的简单示意图。要求,输入书名,就可以输出该商品的分类路径
例如,输入《java编程思想》,输出Java编程思想-->编程语言-->计算机与互联网-->科技-->图书
问题分析
在关系型数据库中,保存当前商品时,同时保存商品(或者商品类别)的父类别。当然,在真实的项目中,一般使用一张表保存商品信息,另一张表存放类型信息,在我的例子中,商品和商品类别没有进行区分。同时,我采用了文件结构保存数据。
类别名称 类型编号 父类别编号
图书 1001 null
教育 2001 1001
文艺 2005 1001
科技 2002 1001
欧美文学 3003 2005
古典诗词 3009 2005
计算机与互联网 3052 2002
编程语言 4011 3052
系统架构 4013 3052
Java编程思想 5023 4011
代码演示
文件读入
ArrayList<Object> array = new ArrayList();
if(file.isFile() && file.exists()){
InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt;
while((lineTxt = bufferedReader.readLine()) != null){
String [] strArray = lineTxt.split("\\s+");
array.add(strArray);
}
read.close();
}
这样可以把文本文件以list的形式保存,其中每个list元素是一个长度为三的String数组
对象封装
public ArrayList<ProductInfo> GetObject() {
ArrayList<ProductInfo> productList = new ArrayList();
readTextFile textfile = new readTextFile();
ArrayList list = textfile.readFile("C:\\Users\\admin\\Desktop\\info.txt");
Iterator item = list.iterator();
//将每个商品封装成对象
while (item.hasNext()) {
String[] info = (String[]) item.next();
ProductInfo product = new ProductInfo(info[0], info[1], info[2]);
productList.add(product);
}
return productList;
}
这个方法调用了读文件的方法,这样可以得到新的list对象,list的元素是一个People对象,这么做和上面的list并没有本质的区别,但可以使我们可以更方便、清晰的访问每个商品的信息
public void GetChain(String num, ArrayList<ProductInfo> list) {
Iterator item = list.iterator();
//使用迭代算法
while (item.hasNext()) {
ProductInfo info = (ProductInfo) item.next();
while ((info.getNum().equals(num) == true)) {
num = info.getFatherNum();
System.out.print(info.getName() + "-->");
GetChain(num, list);
}
}
}
这个过程是对ArrayList数据结构的迭代访问,通过当前商品的ID找到父类商品的类型信息。
测试代码
public static void main(String[] args) {
Test TreeChain = new Test();
ArrayList<ProductInfo> productList = TreeChain.GetObject();
TreeChain.GetChain("5023",productList);
System.out.println();
TreeChain.GetChain("3009",productList);
}
输出:
Java编程思想-->编程语言-->计算机与互联网-->科技-->图书
古典诗词-->文艺-->图书
在最后的迭代过程中,我们采用的是遍历list中的元素,渠道父亲ID,再次遍历,时间复杂度较高;如果把这个结构组织成链表,便利是会简单的多。