List Iterator for()

本文介绍了如何使用Java的ArrayList进行元素添加及遍历,并展示了通过PreparedStatement执行参数化SQL查询,将结果集保存到自定义Bean对象中并以List形式返回的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Collection c = new ArrayList();
c.add("abc");
c.add("xyz");
for(Iterator it = c.iterator(); it.hasNext(); ) {
   String s = (String)it.next();
   System.out.println(s); }

++++++++++++++++++++++++++++返回集保存到Bean,以List形式返回+++++++++++++++++++++
 
String sql = "SELECT NO,NAME FROM TABLE_NAME WHERE NO = ? AND NAME = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, No);
ps.setString(2, Name);
ResultSet rs = ps.executeQuery();

List list = new LinkedList();
while (rs.next()) {
     no = rs.getString("NO").trim();
     name = rs.getString("NAME").trim();

    Bean personBean = new PersonBean();
    personBean.setNo(no);
    personBean.setName(name);

    list.add(personBean);
  }
  return list;
}
### Java List Iterator Usage and Example In Java, an `Iterator` is used to traverse through the elements of a collection object such as a `List`. The `Iterator` interface provides methods like `hasNext()`, which returns true if there are more elements in the iteration, and `next()`, which retrieves the next element in the sequence. For lists specifically, one can obtain an iterator by calling the `iterator()` method on any class implementing the `List` interface. Here’s how it works: ```java import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Main { public static void main(String[] args) { // Create a new ArrayList (which implements List) List<String> myList = new ArrayList<>(); // Add some items into our list myList.add("Apple"); myList.add("Banana"); myList.add("Orange"); // Obtain an Iterator instance from the List Iterator<String> myIterator = myList.iterator(); while(myIterator.hasNext()) { // Check whether there's another item available String fruit = myIterator.next(); // Get the current item System.out.println(fruit); // Print out each item found during traversal } } } ``` The above code snippet demonstrates obtaining an iterator using the `iterator()` method provided by classes that implement the `List` interface[^4]. Each call to `myIterator.next()` advances the cursor position within the underlying data structure until no further entries remain. Additionally, iterators support removal operations via their own `remove()` function without directly modifying the original container outside safe boundaries established when creating them. However, adding or removing elements elsewhere may throw exceptions due to concurrent modification issues unless explicitly supported by specialized implementations.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值