【问题标题】:How Do I Convert A String To A Generic Type?如何将字符串转换为泛型类型?
【发布时间】:2020-11-10 02:24:46
【问题描述】:

我打算创建一个类来读取包含员工信息(ID 号、姓名和电子邮件)的文本文档,并将信息转换为包含两个组件的 Map:带有 ID 号的字符串和 Employee 对象名称和电子邮件,由一个空格分隔(与文本文档中的两个空格相反)。我(几乎)通过创建一个程序来解决这个问题,该程序成功地遍历文本文档,将每一行分成三部分,除以每组两个连续的空格,然后将最后两部分加在一起。但是,由于此时最后一部分是字符串格式,我需要将其转换为 Employee 对象,然后才能将其插入 HashMap,但我在来这里之前所做的所有研究都表明不能将字符串转换为泛型,我想不出任何其他方法来做到这一点。

这是我要遵守的类提供的(不可编辑的)主类:

public static void main(String[] args)
  {
    Map<String, Employee> data = Employee.load();
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Enter ID of employee you're looking for");
    String id = keyboard.nextLine();
    System.out.println(data.get(id));
  }

这是我尝试创建要返回的正确 HashMap 的类:

public static Map<String,Employee> load() {
        File f=new File("employees.txt");
        Map<String,Employee> result=new LinkedHashMap<>();
        String ID = null;
        String name = null;
        String email = null;
        String b;
        try {
            BufferedReader in = new BufferedReader(new FileReader(f));
            String line;
            String[] values;
            int i=0;
            while(((line=in.readLine())!=null)){
                line=in.readLine();
                values= line.split("  ");
                if (i>0){
                //this is meant to ignore the first line, as it contains irrelevant information
                ID=values[0];
                name=  values[1];
                email=values[2];}
                i++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        b=name+" "+email;
        result.put(ID, (Employee) b); //"(Employee) b" has an error that reads:  
        //Inconvertible types; cannot cast 'java.lang.String' to 'Employee'
        return result;
    }
}

【问题讨论】:

    标签: java generics hashmap


    【解决方案1】:

    您需要调用Employee 构造函数,创建一个 Employee 对象,然后适当地设置其字段——通过将它们传递给构造函数或调用setter。所以你的代码可能看起来像,例如,

    result.put(ID, new Employee(name, email));
    

    ...虽然你会发现它应该进入while 循环,而不是在try/catch 之后。

    【讨论】:

      【解决方案2】:
      result.put(ID, new Employee(name, email))
      

      for 员工调用 new Employee(/你的构造函数的参数/)

      【讨论】:

        猜你喜欢
        • 2019-09-10
        • 2021-10-25
        • 2012-12-14
        • 1970-01-01
        • 2011-06-29
        • 2010-09-05
        • 2021-09-23
        • 1970-01-01
        • 2012-09-19
        相关资源
        最近更新 更多