HashMap 中的 ArrayIndexOutofBoundException for setintersection

ArrayIndexOutofBoundException in HashMap for setintersection

class swap {
public static void main(String[] args) throws FileNotFoundException {
    Scanner s1 = new Scanner(new FileReader("C:/Users/USER/Desktop/Saumil/Saumil/FP.data"));
    Scanner s2 = new Scanner(new FileReader("C:/Users/USER/Desktop/Saumil/Saumil/FP1.data"));
    HashMap<String, String> map1 = new HashMap<String, String>();
    HashMap<String, String> map2 = new HashMap<String, String>();
    while (s1.hasNextLine()) {
        String[] columns = s1.nextLine().split("");
        System.out.println("hi");
        map1.put(columns[0], columns[1]);
    }
    while (s2.hasNextLine()) {
        String[] columns = s2.nextLine().split("");
        System.out.println("123");
        map1.put(columns[0], columns[1]);
    }

    System.out.println(map1);
    try {
    //Map result = new HashMap();

        Set<String> s = new HashSet<String>(map1.keySet());
        System.out.println("1234");
        s.retainAll(map2.keySet());
        System.out.println(s);


        FileOutputStream fos = new FileOutputStream("C:/Users/USER/Desktop/Saumil/Saumil/output.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);   
        oos.writeObject(s); // write list to ObjectOutputStream
        oos.close(); 
        System.out.println("hi");
    } catch(Exception ex) {
        ex.printStackTrace();
    }
    //Collection intersection=CollectionUtils.intersection(map1.keySet(),map2.keySet());
    s1.close();
    s2.close();

我正在尝试将两个散列相交 map.Each 散列图从基本上有两列的文件中获取数据。

它在第-14行给我arrayindexoutof bound异常 即 map1.put(列[0], 列[1]);

我不明白为什么它给我这样的异常

我会检查您的数据文件并确认它们的数据格式正确。 我的猜测是他们有一些不正确的数据。 您正在创建一个字符串对象数组,

String[] columns = s1.nextLine().split("");

并且您期望此数组中包含 2 个字符串对象。然而,如果文件有错误行,情况可能并非总是如此。

例如,文件中的一行可能是这样的(第 3 行)

1 col1value1   col1value2
2 col2value1   col2value2
3 col3value1
4 col4value1   col4value2

当您将每一行转换为一个数组对象时,它会在文件中每行生成一个数组。然而,当到达第 3 行时,它会生成一个包含一个对象的数组。

当您尝试访问

columns[1]

在这种情况下它会抛出 java.lang.ArrayIndexOutOfBoundsException。

作为调试步骤,也许在访问这些数组上的值之前打印并检查数据。

或者做一个 try and catch 块,然后在 catch 块下面打印出它跌倒的输入行。

String tmpStr1 = "";

try {
     tmpStr1 = s1.nextLine();
     columns = tmpStr1.split("");
     //access array items
}
catch (ArrayIndexOutOfBoundsException aEx) {

    System.out.println(aEx.getMessage());
    //print the whole like that was read from the file
    //this will help you to understand what went wrong
    System.out.println(tmpStr1);
}