会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1936楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1937楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1938楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1939楼

请问老师,我的List提示 java.util.ConcurrentModificationException

已经换了其他的遍历方法,但是还是无法正常add添加

package com.bjsxt.test;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.bjsxt.pojo.Integral;

public class RandomNumAndName {
    static String name = "";
    static int ID = 1000;

    public static void main(String[] args) {
        List<Integral> integralList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Integral integral2 = MakeOne();
            if (integralList.size() > 0) {
                String str1 = integral2.getName();
                // 这里的报错ConcurrentModificationException
                // for (Integral integral : integralList) {
                // String str2 = integral.getName();
                // if(!(str2.equals(str1))) {
                // integralList.add(integral2);
                // System.out.println("添加成功");
                // }
                // }
                // 换一个方法遍历
//                for (int j = 0; j < integralList.size(); j++) {
//                    Integral temp = integralList.get(j);// 获取每一个Example对象
//                    String str2 = temp.getName();
//                    if (!(str2.equals(str1))) {
//                        integralList.add(integral2);
//                        System.out.println("添加成功");
//                    }
//                }
//                 最后一种
                 for (Iterator iterators = integralList.iterator(); iterators.hasNext();) {
                 Integral example = (Integral) iterators.next();// 获取当前遍历的元素,指定为Example对象
                 String str2 = example.getName();
                 if (!(str2.equals(str1))) {
                 integralList.add(integral2);
                 System.out.println("添加成功");
                 }
                 }

            } else {
                integralList.add(integral2);
            }
        }
        System.out.println(integralList);

    }

    //
    // public static List<Integral> addList(int i) {
    // String str2 = "";
    // List<Integral> tempi = new ArrayList<>();
    // Integral integral2 = MakeOne();
    // str2 = integral2.getName();
    // for (int j = 0; j < i; j++) {
    // if (tempi.size() != 0) {
    // for (Integral integral1 : tempi) {
    // if (!(integral1.getName().equals(integral2.getName()))) {
    // System.out.println(integral1.getName());
    // tempi.add(integral2);
    // }
    // }
    // } else {
    // tempi.add(integral2);
    // }
    // System.out.println(str2);
    // }
    //
    // return tempi;
    // }

    /**
     * 随机出来一个人的积分
     * 
     * @return
     */
    public static Integral MakeOne() {
        int jif = 0;
        Integral temp = new Integral();
        for (int j = 1; j <= 3; j++) {
            name = name + (char) (Math.random() * 26 + 'a');
        }
        jif = (int) (Math.random() * 200);
        if (jif % 2 != 0) {
            temp.setGender("男");
        } else {
            temp.setGender("女");
        }
        temp.setID(ID);
        temp.setName(name);
        temp.setIntegralpart(jif);
        ID++;
        name = "";
        return temp;
    }

    /**
     * 随机生成时间
     * 
     * @param beginDate
     * @param endDate
     * @return
     */
    private static Date randomDate(String beginDate, String endDate) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date start = format.parse(beginDate);// 构造开始日期
            Date end = format.parse(endDate);// 构造结束日期
            // getTime()表示返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
            if (start.getTime() >= end.getTime()) {
                return null;
            }
            long date = random(start.getTime(), end.getTime());
            return new Date(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static long random(long begin, long end) {
        long rtn = begin + (long) (Math.random() * (end - begin));
        // 如果返回的是开始时间和结束时间,则递归调用本函数查找随机值
        if (rtn == begin || rtn == end) {
            return random(begin, end);
        }
        return rtn;
    }
}

请问如何能正常的添加元素?

JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1940楼
JAVA 全系列/第三阶段:数据库编程/MySQL数据库的使用 1941楼
JAVA 全系列/第三阶段:数据库编程/MySQL数据库的使用 1942楼

create table numbers
(
	id int auto_increment primary key,
	num int not null,
	type varchar(2)
);

我使用的是mySql,已经把id设置为自动增长

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

/**
 *使用PreparedStatement批处理数据
 *将2~1000之间的数字插入数据库,并记录数字的类型(质数还是合数)
 *
 */
public class TestNum {
	
	public static void main(String[] args) throws Exception {
		int num=1000;
		long startTime=System.currentTimeMillis();
//		insertNum1(num);//	使用Statement插入数字
//		System.out.println("使用statement耗时:"+(endTime-startTime));
		
		insertNum2(num);//	使用PreparedStatement插入数字
		long endTime=System.currentTimeMillis();
		System.out.println("使用PreparedStatement耗时:"+(endTime-startTime));
	}
	/**
	 * 使用PreparedStatement插入数字,批处理
	 * @throws Exception 
	 */
	private static void insertNum2(int num) throws Exception {		
		Connection conn = JDBCUtils.getConnection();
		String sql="insert into numbers  values(null,?,?)";
		PreparedStatement state=conn.prepareStatement(sql);
		conn.setAutoCommit(false);//关闭自动提交
		for(int i=2;i<=num;i++) {
			//绑定参数
			JDBCUtils.bind(state,i,getType(i));
			//加入批处理
			state.addBatch();		
		}		
		//统一执行批处理
		state.executeBatch();
		conn.commit();
		JDBCUtils.relese(state, conn);
		
	}
	/**
	 * 使用Statement插入数字,并且只开关一次连接
	 * @throws Exception 
	 * 
	 */
	private static void insertNum1(int num) throws Exception {
		Connection conn=JDBCUtils.getConnection();
		Statement state=conn.createStatement();
		for(int i=2;i<=num;i++) {
			String sql="insert into numbers values(null,"+i+",'"+getType(i)+"')";
			state.executeUpdate(sql);
		}		
		JDBCUtils.relese(state, conn);
	}
	/**
	 * 判断数字类型
	 * @return
	 */
	private static String getType(int num) {
		if(num<4) {
			return "ZS";
		}
		for(int i=2;i<Math.sqrt(num);i++) {
			if(num % i==0) {
				return "HS";
			}
		}
		return "ZS";
	}
}

在测试PreparedStatement时,就只是需要绑定两个参数了,将id那个设置为null,运行时出现异常,这是为什么呢?

image.png

JAVA 全系列/第三阶段:数据库编程/JDBC技术(旧) 1946楼
JAVA 全系列/第三阶段:数据库编程/Oracle 数据库的使用 1948楼
JAVA 全系列/第三阶段:数据库编程/SQL 语言 1949楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637