我正在寻找一种方法来将
Java中保存的所有关键字检索到某种数据结构中.例如:“for,while,if,else,int,double等”
我需要对字符串进行名称验证,具体来说,我需要确保它不等于任何java关键字.
有没有一种特定的方法可以将所有关键字检索到一个数据结构中?或者我是否需要构建一个包含所有这些关键字的正则表达式字符串:“for | while | if | …”并尝试匹配我的字符串?
谢谢
解决方法
从
axis.apache.org起
基本上,对关键字进行预排序并将其存储在一个数组中,并在关键字上使用Arrays.binarySearch以获得good’ol O(logn)复杂度
import java.util.Arrays; public class MainDemo { static final String keywords[] = { "abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","extends","false","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","null","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","true","try","void","volatile","while" }; public static boolean isJavaKeyword(String keyword) { return (Arrays.binarySearch(keywords,keyword) >= 0); } //Main method public static void main(String[] args) { System.out.println(isJavaKeyword("void")); } }
输出:
真正