如何更新ArrayList元素的一部分?

时间:2013-07-10 03:44:28

标签: java arraylist

背景故事:我是一个在大学里很少有OOP教学的网络人。现在我陷入了“一周中的Java”工作训练课程,试图漂浮。

我需要一个ArrayList,每个元素都有这四个“属性(?)”:Name,ProductID,Price,Expiration Date。我想允许用户选择他们想要更新的元素,然后选择他们想要更新的元素的“属性”。我想了一会儿ArrayList.set(索引,元素)可以工作,但是现在我认为这将更新整个元素,而不仅仅是价格或只是名称,如果需要。

我的一些代码:

ArrayList < Prod > pList = new ArrayList < Prod > ();
pList.add(new Prod("Tomato", "P101", 10, "4 days"));
//etc etc

int index = 0;
for (Prod p: pList)
{
    System.out.println("");
    System.out.println("Index : " + String.valueOf(index++));
    System.out.println("Name : " + p.getName());
    System.out.println("ID : " + p.getId());
    System.out.println("Price : " + p.getPrice());
    System.out.println("Expiration Date : " + p.getExpDate());
}

Scanner input = new Scanner(System. in );
System.out.println("Which Index would you like to adjust?");
int change = input.nextInt();

System.out.println("What would you like to change about Index " + change + "?");
System.out.println("Enter 1 for the Name.");
System.out.println("Enter 2 for the Product ID.");
System.out.println("Enter 3 for the Price.");
System.out.println("Enter 4 for the Expiration Date.");
int type = input.nextInt();

if (type == 1)
{
    System.out.println("What would you like to change the name to?");
    String newName = input.nextLine();
    pList.set(change, newName);
}

我确实有setter和getters,并且所有工作都已正确设置并可以编译;问题是如何调整名称,或PID等。我相信这是非常具体的,而不是像在这里提出问题的介绍一般,但我不知道如何解决这个问题;我已经工作了几个小时。

5 个答案:

答案 0 :(得分:1)

Scanner input = new Scanner(System.in);
System.out.println("Which Index would you like to adjust?");
int change = input.nextInt();

System.out.println("What would you like to change about Index " + change + "?");
System.out.println("Enter 1 for the Name.");
System.out.println("Enter 2 for the Product ID.");
System.out.println("Enter 3 for the Price.");
System.out.println("Enter 4 for the Expiration Date.");
int type = input.nextInt();
Prod p = pList.get(change);

if(type==1){ 
   p.setName(input.nextLine());
}
else if(type==2){
   p.setId(input.nextLine());
}
///and so on

答案 1 :(得分:1)

System.out.println("Which Index would you like to adjust?");
int change = input.nextInt();

Prod product = pList.get(change);

if(type==1){
   System.out.println("What would you like to change the name to?");
   String newName = input.nextLine();
   product.setName(newName);
}

答案 2 :(得分:1)

只需获取索引change处的元素并调用相关的setter,例如:

Prod p = pList.get(change);
switch (type)
{
    case 1:
        p.setName(newName);
        break;
    case 2:
        p.setProductId(newName);
        break;
    // etc
}

答案 3 :(得分:0)

如果你在索引处获取对象并尝试更新它,那么它应该可以工作。像这样:

//Fetch the prod need to be updated
Prod prodToUpdate = pList.get(index);
//update the attributes of the fetched prod like this
prodToUpdate.setName("updatedName");

答案 4 :(得分:0)

您可以使用类似pList.get(change).setName()的内容来更新Prod对象的特定字段。