关于java.util.NoSuchElementException错误的一则例子

本文通过一个从A文件复制到B文件并去除重复行的示例,探讨了遇到`java.util.NoSuchElementException`错误的原因。问题出现在尝试使用迭代器`next()`方法时,未正确检查`hasNext()`。解决方案是确保在调用`next()`前检查`hasNext()`,或者在循环中只调用一次`next()`。

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

写了一个从A文件复制到B文件的例子,其中要求去掉重复的行。

于是想到了Set,这本来是很容易的事情,结果在向外写数据时抱错

java.util.NoSuchElementException

网络上反复查证也没有相关的内容,于是自己慢慢的找,终于找到了。下面写出这个错误的例子及分析,希望能及时的帮助和我同样犯了小错误的菜鸟!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Step01 {

 public static void main(String[] args) {
  Set<String> set = new HashSet<String>();
  File in = new File("Answer0712/aaa.txt");
  File out = new File("Answer0712/bbb.txt");
  InputStream is = null;
  OutputStream os = null;
  try {
   is = new FileInputStream(in);
   os = new FileOutputStream(out);
   BufferedReader br = new BufferedReader(new InputStreamReader(is));
   while (true) {
    String str = br.readLine();
    if (str == null)
     break;
    set.add(str);
   }
   // Iterator i = set.iterator();
   // while(i.hasNext()){
   // System.out.println("Null值判断:"+i.next());
   // }
   PrintWriter pw = new PrintWriter(new BufferedWriter(
     new OutputStreamWriter(os)), true);
   Iterator i = set.iterator();
   while (i.hasNext()) {
    System.out.println(i.next());  //这一句是罪魁祸首
    pw.println(i.next());
   }
   pw.flush();
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    is.close();
    os.close();
   } catch (IOException e) {
    e.printStackTrace();
   }

  }

 }
}

文章中标示黄色的那一句,本来是要打印出来,在控制台看看所写的数据是否正确。

结果就出现了java.util.NoSuchElementException的错误提示 ,就是黄色的那一句,多了一个 迭代器的next()。

所以错了。去掉它就好了,或者改为

while (i.hasNext()) {
    String ss = (String) i.next();
    System.out.println(ss);
    pw.println(ss);
   }都可以解决问题。
 

### Java `Collections.min` 方法使用说明 #### 方法签名 Java 中 `Collections.min` 方法用于返回给定集合中的最小元素。此方法有两种重载形式: - 对于自然顺序的元素: ```java public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) ``` - 当需要自定义比较器时: ```java public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) ``` 这两种方式分别适用于不同的场景[^2]。 #### 参数描述 - `coll`: 要从中找到最小元素的集合,不能为空。 - `comp`(仅限第二种重载): 自定义比较器实例,在不适用自然排序的情况下提供定制化排序逻辑。 #### 返回值 返回集合中按指定顺序排列的第一个元素;如果存在多个相同最小值,则任意返回其中一个。 #### 异常处理 当传入空集合作为参数时会抛出 NoSuchElementException 异常。此外,对于泛型类型的对象,如果没有实现Comparable接口或者提供的Comparator不符合预期也会引发ClassCastException异常。 #### 示例代码 下面展示了一个简单的例子来演示如何利用 `Collections.min()` 来获取列表里的最小整数值: ```java import java.util.*; public class MinExample { public static void main(String[] args) { List<Integer> numbers = new ArrayList<>(); numbers.add(3); numbers.add(-1); numbers.add(8); Integer minValue = Collections.min(numbers); System.out.println("The minimum value is: " + minValue); // 输出 The minimum value is: -1 } } ``` 对于更复杂的数据结构比如自定义类的对象,可以通过传递合适的 comparator 实现特定属性上的极值计算[^4]: ```java import java.util.*; class Person implements Comparable<Person>{ private final String name; private final int age; public Person(String n, int a){ this.name=n; this.age=a; } @Override public int compareTo(Person otherPerson){ return Integer.compare(this.age,otherPerson.getAge()); } public String toString(){ return "[Name="+this.name+", Age="+this.age+"]"; } public int getAge(){return this.age;} } public class CustomMinExample { public static void main (String []args){ List<Person> people=new ArrayList<>(Arrays.asList( new Person("Alice",30), new Person("Bob",25))); Person youngest=Collections.min(people,new Comparator<Person>() { @Override public int compare(Person p1, Person p2) { return Integer.valueOf(p1.getAge()).compareTo(p2.getAge()); } }); System.out.println(youngest); // 输出 [Name=Bob, Age=25] } } ```
评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值