不定期更新的一些Java小的知识点,小技巧

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值