java 类型不匹配:无法从元素类型 Object 转换为 String
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11926578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Type mismatch: cannot convert from element type Object to String
提问by cw.prime
Can some one take a look at this and tell me why I am getting this error. I am trying to pull a table from a Mysql database and print it to a text file. I gives me the error listed above.
有人可以看看这个并告诉我为什么我会收到这个错误。我正在尝试从 Mysql 数据库中提取一个表并将其打印到一个文本文件中。我给了我上面列出的错误。
package db;
import java.io.*;
import java.sql.*;
import java.util.*;
public class TableToTextFile {
public static void main(String[] args) {
List<int[]> data = new ArrayList();
try {
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from employee");
while (rs.next()) {
String id = rs.getString("emp_id");
String name = rs.getString("emp_name");
String address = rs.getString("emp_address");
String contactNo = rs.getString("contactNo");
data.add(id + " " + name + " " + address + " " + contactNo);
}
writeToFile(data, "Employee.txt");
rs.close();
st.close();
} catch (Exception e) {
System.out.println(e);
}
}
private static void writeToFile(java.util.List list, String path) {
BufferedWriter out = null;
try {
File file = new File(path);
out = new BufferedWriter(new FileWriter(file, true));
for (String s : list) {
out.write(s);
out.newLine();
}
out.close();
} catch (IOException e) {
}
}
}
回答by adarshr
Possibly because your list has been declared to accept integer arrays and you're passing in a string.
可能是因为您的列表已被声明为接受整数数组,并且您正在传入一个字符串。
List<int[]> data = new ArrayList();
Change it to accept strings instead.
将其更改为接受字符串。
List<String> data = new ArrayList<>();
A much better and more object-oriented design would be to create a class called Employee
and use it instead.
一个更好、更面向对象的设计是创建一个名为的类Employee
并使用它。
public class Employee {
private String id;
private String name;
...
}
List<Employee> data = new ArrayList<>();