Reputation: 596
I have a method like this:
public List<Employee> getEmployeeListViaSurname(String surname) {
List<Employee> EmployeeListViaSurname = new ArrayList<Employee>();
int id = -1;
String name = "";
try {
PreparedStatement pst = null;
pst = con.prepareStatement("select * from Employee where surname = ?");
pst.setString(1, surname);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
id = rs.getInt("id");
name = rs.getString("name");
//EmployeeListViaSurname.add(id, name); <---- error
}
} catch (Exception e) {
System.err.println(e);
}
return EmployeeListViaSurname;
}
Could somebody show me how can I add employee via surname.
In example getEmployeeListViaSurname("George");
Upvotes: 0
Views: 91
Reputation: 3599
EmployeeListViaSurname
is a java list that holds Employee
objects as shown in its type declaration and initialization (the name of the type in the < > brackets):
List<Employee> EmployeeListViaSurname = new ArrayList<Employee>();
The java sdk documentation contains the all of the information for the standard java libraries, telling you the classes available, method signatures and how to use them. In this case see the documentation for List.add(E) (Google for java api docs List
or java api docs ArrayList
).
Notice that it takes a single E
object, which should be the same type of object the list is parameterized over, which in your case is Employee
. But you are passing it an int
and a String
, so on trying to compile it will fail, and you will get a syntax error.
To fix this first instantiate a new Employee
object using one of its constructors and then pass that to the add
method. E.g. something like:
while (rs.next()) {
id = rs.getInt("id");
name = rs.getString("name");
Employee employee = new Employee(id, name, surname);
EmployeeListViaSurname.add(employee);
}
The precise details for how you create and initialize an Employee
object depends on the Employee
class definition.
A constructor is a special method without a return type that has the same name as the class and will look something like public Employee() { ... }
or public Employee(String id, String name, String surname) { ... }
. If it only has a parameterless constructor use it and then set the fields.
If you need more help you'll need to give us the details for the Employee
class.
Upvotes: 2
Reputation: 16060
An ArrayList
contains objects - in your case Employee
objects, of which you must create one to add to the ArrayList - you can't add the attributes directly:
// provided a fitting Employee constructor exists:
EmployeeListViaSurname.add( new Employee( id, name ) );
Cheers,
Upvotes: 1