Java - 混合数组列表?
是否可以在 ArrayList 中存储混合的对象类型?如果是这样怎么办?
这是我到目前为止所尝试过的:
List<Object> list = new ArrayList<Object>();
list.add(new String("Hello World"));
list.add(new Integer(1));
list.add(new Long(1l));
for (i = 0; i < list.size(); i++) {
if (list.get(i) instanceof String){
sqlPreparedStatement.setString((i+1), (String) list.get(i));
} else if (list.get(i) instanceof Integer) {
sqlPreparedStatement.setInt((i+1), (Integer) list.get(i));
} else if (list.get(i) instanceof Long) {
sqlPreparedStatement.setLong((i+1), (Long) list.get(i));
}
}
但它会引发强制转换异常。
预先感谢您的任何意见!
Is it possible to store a mixture of object types in an ArrayList? If so how?
This is what I have tried so far:
List<Object> list = new ArrayList<Object>();
list.add(new String("Hello World"));
list.add(new Integer(1));
list.add(new Long(1l));
for (i = 0; i < list.size(); i++) {
if (list.get(i) instanceof String){
sqlPreparedStatement.setString((i+1), (String) list.get(i));
} else if (list.get(i) instanceof Integer) {
sqlPreparedStatement.setInt((i+1), (Integer) list.get(i));
} else if (list.get(i) instanceof Long) {
sqlPreparedStatement.setLong((i+1), (Long) list.get(i));
}
}
But it throws a casting exception.
Thanks in advance for any input!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是你应该拥有的:
This is what you should have:
很抱歉让您的游行崩溃,但您一开始就不应该使用 3 种(或任何)不同类型的 ArrayList。如果信息相关,则创建一个保存相关信息的类,并创建一个仅保存一种类型的ArrayList:该类的对象。
编辑1:
例如,假设一个类像这样保存数据:
并像这样使用:
Sorry to crash your parade, but you shouldn't be using an ArrayList of 3 (or any) different types to begin with. If the information is related, create a class that holds the related information and create an ArrayList that holds only one type: objects of this class.
Edit 1:
For instance say a class to hold the data like so:
and used like so:
你为什么让这件事变得如此困难?
PreparedStatement
有一个setObject()
方法 - 只需使用它:注意:java SQL API 从 1 开始计数,而不是从零开始,因此列编号为 1。 ..size() 而不是 0...size()-1
Why are you making this so hard?
PreparedStatement
has asetObject()
method - just use that:NOTE: The java SQL API counts everything from 1, not from zero, so columns are numbered 1...size() and not 0...size()-1