编程中的小技巧,持续更新

下面是是读开源项目源码,JDK源码,Android系统源码小技巧


使用do{ } while(0)

int foo()
{
    somestruct* ptr = malloc(...);
    do{
        dosomething...;
        if(error)
        {
            break;
        }
 
        dosomething...;
        if(error)
        {
            break;
        }
        dosomething...;
    }while(0);
 
    free(ptr);
    return 0;
}

1.替代{},实现局部作用域.在一些C的实现里也可以用.
2,避免使用goto对程序流进行统一的控制:
有些函数中,在函数return之前我们经常会进行一些收尾的工作,比如free掉一块函数开始malloc的内存,用break做跳出.
3,当你执行一段代码到一半,想跳过剩下的一半的时候,如果你正处于do while循环中,则能用break达到这个目的
4,定义一个单独的函数块来实现复杂的操作:
当你的功能很复杂,变量很多你又不愿意增加一个函数的时候,使用do{}while(0);,
将你的代码写在里面,里面可以定义变量而不用考虑变量名会同函数之前或者之后的重复。


连续连接n次直至成功(例如socket重连):

private static void writeLmkd(ByteBuffer buf) {
    //当socket打开失败会尝试3次
    for (int i = 0; i < 3; i++) {
        if (sLmkdSocket == null) {
                if (openLmkdSocket() == false) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ie) {
                    }
                    continue;
                }
        }
        try {
            //将buf信息写入lmkd socket
            sLmkdOutputStream.write(buf.array(), 0, buf.position());
            return;
        } catch (IOException ex) {
            try {
                sLmkdSocket.close();
            } catch (IOException ex2) {
            }
            sLmkdSocket = null;
        }
    }
}

文件按序命名(下载文件名称按序号命名):

/* 
         * This number is used to generate partially randomized filenames to avoid 
         * collisions. 
         * It starts at 1. 
         * The next 9 iterations increment it by 1 at a time (up to 10). 
         * The next 9 iterations increment it by 1 to 10 (random) at a time. 
         * The next 9 iterations increment it by 1 to 100 (random) at a time. 
         * ... Up to the point where it increases by 100000000 at a time. 
         * (the maximum value that can be reached is 1000000000) 
         * As soon as a number is reached that generates a filename that doesn't exist, 
         *     that filename is used. 
         * If the filename coming in is [base].[ext], the generated filenames are 
         *     [base]-[sequence].[ext]. 
         */  
         int sequence = 1;  
         for (int magnitude = 1; magnitude < 1000000000; magnitude *= 10) {  
             for (int iteration = 0; iteration < 9; ++iteration) {  
                 fullFilename = filename + sequence + extension;  
                 if (!new File(fullFilename).exists()) {  
                     return fullFilename;  
                 }  
                 Log.v(LOG, "file with sequence number " + sequence + " exists");  
                 sequence += sRandom.nextInt(magnitude) + 1;  
             }  
         }  

交换两个List元素

public static void swap(List<?> list, int i, int j) {
        final List l = list;
        l.set(i, l.set(j, l.get(i)));
    }

 时间换空间,交换2个数
         Int a,b
         a=a+b;b=a-b;a=a-b;


数组避免越界处理


table[hash&(table.length-1)]

<pre name="code" class="java">public void clear() {
        int h = head;
        int t = tail;
        if (h != t) { // clear all cells
            head = tail = 0;
            int i = h;
            int mask = elements.length - 1;
            do {
                elements[i] = null;
                i = (i + 1) & mask;
            } while (i != t);
        }
    }



数学运算
在数字没有溢出的前提下,对于正数和负数,左移一位都相当于乘以2,左移n位就相当于乘以2的n次方
右移一位相当于除2,右移n位相当于除以2的n次方。
int low = fromIndex;
int high = toIndex - 1;
int mid = (low + high) >>> 1;
移位时,移出的位数全部丢弃,移出的空位补入的数与左移还是右移有关。如果是左移,则规定补入的数全部是0;
如果是右移,还与被移位的数据是否带符号有关。若是不带符号数,则补入的数全部为0;
若是带符号数,则补入的数全部等于原数的最左端位上的原数(即原符号位)。
Java也添加了一种“无符号”右移位运算符(>>>),它使用了“零扩展”:无论正负,都在高位插入0。这一运算符是C或C++没有的。


不断更新中。。。

原文地址:https://www.cnblogs.com/happyxiaoyu02/p/6150733.html