我在for-each循环中遇到此错误:
“类型不匹配:无法从元素类型对象转换为员工”
private static HashMap<Integer,Employee> employeeDatabase = new HashMap<Integer,Employee>();
public HashMap getEmployeeDatabase() {
return employeeDatabase;
}
for(Employee e: c.getEmployeeDatabase().values())
{
e.print();
}
如果有关系-'Employee'包含int(id),String(name),double(salary)。填充HashMap时,将复制int(id)用作我的HashMap的Integer键。
编辑:问题在于getEmployeeDatabase访问器返回原始类型,谢谢那些回答的人。
对于那些想知道'c'变量的人:
Company c = new Company();
那是它的来历。 Company类的默认构造函数使用私有方法从Scanner填充employeeDatabase。
答案 0 :(得分:3)
您的方法返回类型为raw type。不要使用原始类型。
private static HashMap<Integer,Employee> employeeDatabase = new HashMap<Integer,Employee>();
public HashMap getEmployeeDatabase() {
return employeeDatabase;
}
应该像
private static Map<Integer, Employee> employeeDatabase = new HashMap<>();
public Map<Integer, Employee> getEmployeeDatabase() {
return employeeDatabase;
}
答案 1 :(得分:0)
当您不指定泛型时,假定为对象,然后
// Utility function to get the shipping method Id from order object
function wc_get_shipping_method_id( $order ){
foreach ( $order->get_shipping_methods() as $shipping_method ) {
return $shipping_method->get_method_id();
}
}
// Add coditionally a "reply to" based on shipping methods IDs for specific email notifications
add_filter( 'woocommerce_email_headers', 'add_headers_replay_to_conditionally', 10, 3 );
function add_headers_replay_to_conditionally( $headers, $email_id, $order ) {
// Avoiding errors
if ( ! is_a( $order, 'WC_Order' ) || ! isset( $email_id ) )
return $headers;
// The defined emails notifications to customer
$allowed_email_ids = array('customer_on_hold_order', 'customer_processing_order', 'customer_completed_order');
// Only for specific email notifications to the customer
if( in_array( $email_id, $allowed_email_ids ) ) {
// Local Pickup Plus shipping method
if( wc_get_shipping_method_id( $order ) === 'local_pickup_plus' ){
$headers .= "Reply-to: reply1@webshop.com". "\r\n"; // Email adress 1
}
// Other shipping methods
else {
$headers .= "Reply-to: reply2@webshop.com". "\r\n"; // Email adress 2
}
}
return $headers;
}
实际上是
public HashMap getEmployeeDatabase()
所以
public HashMap<Object, Object> getEmployeeDatabase()
不正确,因为values()将返回
for(Employee e : c.getEmployeeDatabase().values()) {
e.print();
}