1. 如何判断一个map是空的方法
if (map == null || map.size() < 1){
......
}
2. 不要在循环中使用try…catch…
不要在循环中使用 try…catch… ,应该把其放在最外除非不得已。
try(
for(...){
...
}
) catch(){
...
}
3. Java字符串数组初始化和赋值
// 一维数组
String[] str = new String[5]; //创建一个长度为5的String(字符串)型的一维数组
String[] str = new String[]{"","","","",""};
String[] str = {"","","","",""};
String数组初始化区别
首先应该明白java数组里面存的是对象的引用,所以必须初始化才能用;
String[] str = {“1”,“2”,“3”}与String[] str = newString[]{“1”,“2”,“3”}在内存里有什么区别?
编译执行结果没有任何区别。更不可能像有些人想当然说的在栈上分配空间,Java的对象都是在堆上分配空间的。
这里的区别仅仅是代码书写上的:
String[] str = {“1”,“2”,“3”}; 这种形式叫数组初始化式(ArrayInitializer),只能用在声明同时赋值的情况下。
而 String[] str = new String[]{“1”,“2”,“3”}是一般形式的赋值,=号的右边叫数组字面量(ArrayLiteral),数组字面量可以用在任何需要一个数组的地方(类型兼容的情况下)。
如:
String[] str = {"1","2","3"}; // 正确的
String[] str = new String[]{"1","2","3"} // 也是正确的
而
String[] str;
str = {"1","2","3"}; // 编译错误
因为数组初始化式只能用于声明同时赋值的情况下。
改为:
String[] str;
str = new String[] {"1","2","3"}; // 正确了
又如:
void f(String[] str) {
}
f({"1","2","3"}); // 编译错误
正确的应该是:
f(new String[] {"1","2","3"});
还可以
String s=new String[30];
如果没有显式赋值,则系统自动赋默认值null。
PS:
笔者所犯错误为在初始化数组的时候定义为String[] str = newString[]{},如此定义相当于创建了创建一个长度为0的String(字符串)型的一维数组。在后期为其赋值的时候str[0]=“A”,就会抛出异常。
4. Java数组中查找指定的元素
可以使用JDK的useArraysBinarySearch()方法:
private static boolean useArraysBinarySearch(String[] arr, String targetValue) {
int a = Arrays.binarySearch(arr, targetValue);
if(a >= 0)
return true;
else
return false;
}
5. Java常见异常
英文 | 中文翻译 |
---|---|
NullPointerException | 空指针引用异常 |
ClassCastException | 类型强制转换异常。 |
IllegalArgumentException | 传递非法参数异常。 |
ArithmeticException | 算术运算异常 |
ArrayStoreException | 向数组中存放与声明类型不兼容对象异常 |
IndexOutOfBoundsException | 下标越界异常 |
NegativeArraySizeException | 创建一个大小为负数的数组错误异常 |
NumberFormatException | 数字格式异常 |
SecurityException | 安全异常 |
UnsupportedOperationException | 不支持的操作异常 |
IllegalStateException | 无效状态异常 |
这些是常见的RunTimeException(运行时异常),也就是说,这些异常不需要强制声明会抛出,或者强制捕捉的异常。
url里面的中文转换
String name = new String(request.getParameter("name").getBytes("iso8859-1"),"utf-8");
将对象转换为XML格式的数据
JaxbUtil.convertToXml(ptInfo, "UTF-8") 将对象转换成xml格式;
long型使用L便于区分
long number = 1000L;
MyBatisForEach的写法
DAO层的写法
int deleteByIds(@Param("ids")List<Long> ids);
XML配置文件的写法
<delete id="deleteByIds" parameterType="java.util.ArrayList">
DELETE FROM tp_merchant_role_resource_rel where id in
<foreach item="idItem" collection="ids" index="index" open="(" separator="," close=")">
#{idItem}
</foreach>
</delete>