有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java按函数parametr返回null或字符串,不带if

简单的问题,但找不到答案。我有一个函数

private Srting getStrOrNull(String str){
 if (str==null) return null;
 else{
  return "#"+str+"#";//ANY STRING MODIFICATION
 }
}

我是否可以修改此函数,使其不使用任何if,switch子句?例如使用hashmap等

我会解释我需要它的原因。我在数据库中有1000行,例如,我用这种方法根据每行的状态来确定图标

private HashMap<Int,String> iconPaths;

public String getIconPathByState(int id){
 return iconPaths.get(id)
}

我不使用任何开关和ifs来尽可能快地执行此操作,因为此函数将被调用1000次


共 (3) 个答案

  1. # 1 楼答案

    这是一种有时可以使用的方法,在这个带有“#”+…”的人工示例中,速度会较慢。。。,但主要想法可能有用:

    private final static String getStrOrNull(final String str) throws Exception {
        // first step prepare table for different states:
        // 0 - input value is null
        // 1 - input value is some not null string
        // in single thread application you can move this array out of the function as static variable to avoid memory allocation
        final Callable<String>[] func = new Callable[2];
    
        func[0] = new Callable<String>() {
            @Override
            public String call() {
                return null;
            }
        };
    
        func[1] = new Callable<String>() {
            @Override
            public String call() {
                return str.toLowerCase(); // any other string modification
            }
        };
    
        // now we need to convert our input variable into "state" (0 or 1)
        // to do this we're inserting string into set
        // if string is not null - it will be in map, final size will be 1
        // if string is null - we will remove it via remove(null), final size will be 0
        final Set<String> set = new HashSet<String>();
        set.add(str);
        set.remove(null);
    
        return func[set.size()].call();
    }
    

    以下是将输入变量转换为0或1的另一种方法:

    int i = System.identityHashCode(str); // returns 0 for null, non zero for all other values, you can also use unsafe getaddr
    // converts 0 to 0, any non-zero value to 1:
    int b = ((i >>> 16) & 0xffff) | (i & 0xffff);
    b = ((b >>> 8) & 0xff) | (b & 0xff);
    b = ((b >>> 4) & 0xf) | (b & 0xf);
    b = ((b >>> 2) & 0x3) | (b & 0x3);
    b = ((b >>> 1) & 0x1) | (b & 0x1);
    
    return func[b].call();
    
  2. # 2 楼答案

    代码“#”+str+“#”至少需要 100倍于比较,因此我认为您优化了错误的部分