Java手动释放变量

来源:互联网 发布:清华大数据产业联合会 编辑:程序博客网 时间:2024/05/15 03:37

1.清除StringBuffer中的内容

StringBuffer stringBuffer = new StringBuffer();//添加字符串到StringBuffer中stringBuffer.append('helloworld');    // 取得字符串的长度int  sbuf_length = stringBuffer.length();//删除字符串从0~sb_length-1处的内容 (这个方法就是用来清除StringBuffer中的内容)stringBuffer.delete(0,sb_length);    

另一种方式:

//设置StringBuffer变量的长度为0stringBuffer.setLength(0);           

2.清除hashmap中的内容

使用map提供的clear方法。

实例验证:

HashMap hashMap = new HashMap();hashMap.put("1", "bosslbl");hashMap.put("2", "boss");System.out.println("hashMap: " + hashMap);hashMap.clear();System.out.println("hashMap: " + hashMap);

输出

hashMap: {2=bosslbl, 1=boss}hashMap: {}

3.清除Arraylist中的内容

(1)使用list提供的remove方法

Iterator< String > it = list.iterator();  for(;it.hasNext();) {      it.next();      it.remove();  }

注意:只有使用这一种方式才可以在遍历 list的时候执行删除操作,其他方式都不可以实现,会报:ConcurrentModificationException异常

结果:

  操作前:[a, b, c, d, e, f]    操作后:[]  

(2)使用list提供的clear方法

list.clear();  

结果:

  操作前:[a, b, c, d, e, f]    操作后:[]  

总结:
若要清空list, 则采用clear()方法;
若需要根据条件删除某一个元素,则采用迭代实现,在迭代中进行判断断判,满足条件的执行it.remove()操作;

4.清除set中的内容
(1)使用set提供的remove方法

Set<String> set = new HashSet<String>();  set.add("a");  set.add("bb");  set.add("ccc");  set.add("dddd");  set.add("eeeee");  set.add("ffffff");   Iterator<String> it = set.iterator();  while (it.hasNext()) {      String str = it.next();      if ("dddd".equals(str)) {          it.remove();      }  }  for (String str : set) {      System.out.println(str);  }  

结果:

a  ffffff  eeeee  bb  ccc  

(2)使用set提供的clear方法

set.clear();

总结:
若要清空set, 则采用clear()方法;
若需要根据条件删除某一个元素,则采用迭代实现,在迭代中进行判断断判,满足条件的执行it.remove()操作;

参考文献:
http://www.cnblogs.com/qingblog/archive/2012/06/20/2556263.html
http://blog.csdn.net/corpse2010/article/details/37610059
http://blog.csdn.net/shanliangliuxing/article/details/6858841
http://blog.csdn.net/yin_jw/article/details/39668673

9/12/2017 10:37:45 AM

原创粉丝点击