Java项目源码学习笔记(三):PathMatcher
先来看看内部类Node节点:
private static class Node{ private HashMap<String, Node> mMap; private int mKind = NOT_FOUND; Node addChild(String segment){ if(null == mMap){ mMap = new HashMap<String, Node>(); }else{ Node node = mMap.get(segment); if(node != null)return node; } Node n = new Node(); mMap.put(segment, n); return n; } Node getChild(String segment){ if(mMap == null)return null; return mMap.get(segment); } void setKind(int kind){ mKind = kind; } int getKind(){ return mKind; } }
很显然,这是一个单向链表数据结构:
其中mMap中Node对象指向下一个Node对象。
import java.util.ArrayList; import java.util.HashMap; public class PathMatcher{ public static final int NOT_FOUND = -1; private ArrayList<String> mVariables = new ArrayList<String>(); private Node mRoot = new Node(); public PathMatcher(){ mRoot = new Node(); } public void add(String pattern, int kind){ String[] segments = Path.split(pattern); Node current = mRoot; for(int i = 0; i < segments.length; i++){ current = current.addChild(segments[i]); } current.setKind(kind); } public int match(Path path){ String[] segments = path.split(); mVariables.clear(); Node current = mRoot; for(int i = 0; i < segments.length; i++){ Node next = current.getChild(segments[i]); if(null == next){ next = current.getChild("*"); if(next != null){ mVariables.add(segments[i]); }else{ return NOT_FOUND; } } current = next; } return current.getKind(); } }
add构建了根节点为mRoot的单向链表,之所以Node用HashMap保存链表的下一个节点,是因为mRoot一个根节点指向了很多单向链表分支。mKind是每一条单链表分支的key值,它赋给了最后一个节点。
Path string的最后一个segment是"*",匹配任何字符,同时由mVariables保存这一字符。