zoukankan      html  css  js  c++  java
  • 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保存这一字符。

  • 相关阅读:
    appium---纯web app测试
    appium---元素定位工具
    appium---[ADB] Killing adb server on port 5037报错
    pytest---自定义用例识别规则
    pytest---用例执行顺序
    解决Could not find function xmlCheckVersion in library libxml2问题
    pytest---测试框架初探
    layoutSubviews何时被调用
    'addTimeInterval:' is deprecated: first deprecated in iOS 4.0
    iOS7 表格separatorInset的处理
  • 原文地址:https://www.cnblogs.com/fordreamxin/p/5398821.html
Copyright © 2011-2022 走看看