在unicode中创建一个具有chars长度的数组

时间:2016-05-11 14:25:17

标签: java unicode

我在java中编写代码,每次用户键入1个字符时,它会检查它是否是特殊字符之一

char a = getFromInput();

if(a = '$'){
  //do something

}else if(a = '@'){
  //do something


}else if(a = '#'){
  //do something


}else if(a ='~'){
  //do something


}else if(a ='^'){
  //do something


}else if(a ='&'){
  //do something


}... // the if statements go on 

然而,我觉得这样做效率很低,因为它使用了很多if语句。为了解决这个问题,我提出了一个想法,即使用最后一个特殊字符的unicode索引的长度来创建一个字节数组

byte[] bytes = new byte[1000] 

// the length 1000 is because I thought most of the special characters are 
// index of less that 1000 in unicode UTF-8 mapping

Functor[] functors;

// functors are just objects that i made that contain function

char a = getFromInput();
if(byte[a] >100){
   // do nothing when byte[char] is larger that 100 
}else {
    functors[byte[a]].func();
}

所以基本上我要做的就是使用char变量作为数组的索引。我很好奇的是

  1. 对于用户输入的每个字符,是否会使用100多个if语句?有什么建议吗?

  2. 我知道制作一个阵列会花费更多的内存但是它会比使用多个(吨)if语句更好吗?

2 个答案:

答案 0 :(得分:1)

您应该检查字符范围,而不是检查另一个字符。像

这样的东西
if (a < 'a' && a > 'z') {
    // do something
}

答案 1 :(得分:1)

  

对于用户输入的每个字符,是否会使用100多个if语句?有什么建议吗?

由你决定什么是&#34;好的&#34; ......除非您向我们提供标准。

但是,许多@Parcel // can this be used to serialize **all** implementations ... public interface MyIface { String getProperty1(); int getProperty2(); } public class MyImpl implements MyIface { @ParcelFactory // and can this be used to deserialize the interface? public static MyImpl fromParcelerValues(final String property1, final int property2) { ... } } 语句还有其他各种替代方法:

  • if声明
  • switch语句测试字符范围而不是单个字符
  • 一个if数组,其中字符是数组索引
  • 一系列代码(按字符编制索引),用于将字符映射到您随后打开的代码值(例如SomeFunction
  • 在您使用二进制搜索
  • 搜索的字符字段上排序的自定义SomeEnum类的数组
  • a PairOfCharAndFunction
  • 用于实施基于范围的检查的HashMap<Character, SomeFunction>TreeMap<Character, SomeFunction>:提示TreeMap<Character, SomeEnum>方法。

等等。

  

我知道制作一个阵列会花费更多的内存,但是它会比使用多个(吨)if语句更好吗?

是的,只要数组(或类似的映射数据结构;见上文)只需要设置一次。

理论上,Java JIT编译器在某些情况下可以将floorEntry测试序列转换为等效于if的机器,但我不认为它。< / p>

  

... switch语句通常比if语句快吗?

一般是的。如果没有,JIT编译器会将switch转换为switch语句序列。 (事实上​​,这里有一段时间与代码空间权衡。)

相关问题