欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中的两种for循环介绍

程序员文章站 2023-11-27 19:02:16
复制代码 代码如下: package com.zxd.test; import java.util.list; import org.hibernate.hibernate...
复制代码 代码如下:

package com.zxd.test;
import java.util.list;
import org.hibernate.hibernateexception;
import org.hibernate.query;
import org.hibernate.session;
import org.hibernate.sessionfactory;
import org.hibernate.cfg.configuration;
import com.zxd.bean.house;
import com.zxd.util.queryproperty;
/**
* hql封闭查询的测试类
* @author zhang
*
*/
public class testhouse {
public static void main(string[] args) {
//公共的成员变量
sessionfactory sf = null;
session session = null;
queryproperty qp = new queryproperty();
//封装查询的数据
qp.settitle("%好房%");
qp.setstreet_id("1002");
qp.settype_id("1004");
qp.setlow_price(20);
qp.sethigh_price(200);
qp.setsmall_floorage(50);
qp.setbig_floorage(180);
//hql语句
stringbuffer sb = new stringbuffer();
sb.append("from house where ");
sb.append("(title like :title) ");
sb.append("and (type_id like :type_id) ");
sb.append("and (street_id like :street_id) ");
sb.append("and (price between :low_price and :high_price) ");
sb.append("and (floorage between :small_floorage and :big_floorage)");
try {
//开始执行查询
sf = new configuration().configure().buildsessionfactory();
session = sf.opensession();
query query = session.createquery(sb.tostring());
query.setproperties(qp);
list<house> list = query.list();
//第一种用:的循环
/*for(house house:list){
system.out.println("标题是:"+house.gettitle());
system.out.println("面积是:"+house.getfloorage());
system.out.println("价格是:"+house.getprice());
system.out.println("区是:"+house.getstreet().getdistrict().getname());
system.out.println("街道是:"+house.getstreet().getname());
system.out.println("----------------------------------");
}*/
//第二种循环
for(int i = 0;i<list.size();i++){
system.out.println("标题是:"+list.get(i).gettitle());
system.out.println("面积是:"+list.get(i).getfloorage());
system.out.println("价格是:"+list.get(i).getprice());
system.out.println("区是:"+list.get(i).getstreet().getdistrict().getname());
system.out.println("街道是:"+list.get(i).getstreet().getname());
system.out.println("----------------------------------");
}
} catch (hibernateexception e) {
// todo auto-generated catch block
e.printstacktrace();
}finally{
session.close();
sf.close();
}
}
}

上面例子中的第一种循环是我没有记住的,用了关键字符“:”,一般这种循环是用来对一个集合的遍历上的(list<house>、map)中的用的很方便。

第二种循环是普通的循环我这是java中最常见的一种for循环。