如何在java上返回不同的数组列表类型?

时间:2013-07-10 05:25:50

标签: java

我有一种方法可以在其中创建项目并将其添加到3个数组列表中,其中2个为<String>,另一个为<Integer>。问题是我需要在另一个方法中使用它们(全部3个),这个方法将删除我想从中删除的项目。

这是“添加”方法:

public static void Hire () throws IOException{
    String name;
    String category,st_wage,st_id;
    int wage,id;

    BufferedReader ob_name = new BufferedReader (new InputStreamReader (System.in));
    BufferedReader ob_category = new BufferedReader (new InputStreamReader (System.in));
    BufferedReader ob_wage = new BufferedReader (new InputStreamReader (System.in));
    BufferedReader ob_id = new BufferedReader (new InputStreamReader (System.in));
    //name on name_list[id]
    //cat. on cat_list[id]
    //wage on wage_list[id]
    System.out.println("Driver Name: ");

    name = ob_name.readLine();

    System.out.println("Driver License: ");
    System.out.println("1 - Motorcycle");
    System.out.println("2 - Van");
    System.out.println("3 - Truck");

    category = ob_category.readLine();

    System.out.println("Wage: ");

    st_wage = ob_wage.readLine();
    wage = Integer.parseInt(st_wage);

    System.out.println("Driver ID: ");

    st_id = ob_id.readLine();
    id = Integer.parseInt(st_id);

    ArrayList<String> name_list = new ArrayList<String>();
    name_list.add(id, name);

    ArrayList<String> cat_list = new ArrayList<String>();
    cat_list.add(id, category);

    ArrayList<Integer> wage_list = new ArrayList<Integer>();
    wage_list.add(id, wage);

    Manage();

}

这是“删除”方法:

public static void Fire (ArrayList<String> name_list, ArrayList<String> cat_list, ArrayList<String> wage_list) throws IOException{
    int id;
    BufferedReader ob_id = new BufferedReader (new InputStreamReader (System.in));
    BufferedReader ob_op = new BufferedReader (new InputStreamReader (System.in));
    //name on name_list[id]
    //cat on cat_list[id]
    //wage on wage_list[id]
    System.out.println("Driver ID: ");

    String st_id = ob_id.readLine();
    id = Integer.parseInt(st_id);

    String name = name_list.get(id);

    System.out.println("Are You Sure to fire Driver "+name+"? (Y/N)");

    char op = (char) ob_op.read();

    if(op == 'Y' || op == 'y'){
        name_list.remove(id);

        cat_list.remove(id);

        wage_list.remove(id);
    }

    Manage();

}

1 个答案:

答案 0 :(得分:0)

在列表中添加具有自己索引的元素时,您将获得数组索引超出绑定的异常。根据您的要求,您所需要的只是一个简单的课程

public class Driver {
  public String id ;
  public String name ;
  public String category ;
  public double wage ;

  public Driver(String id, String name) {
    this.id = id;
    this.name =name;
  }  

  // getter and setter methods
}

获取用户的所有输入并将其保存在Map

后,创建一个新的Driver实例
// Key = driverId and value = DriverEntity   
HashMap<String,Driver> map = new HashMap();

此外,您可以使用驱动程序ID添加或删除。