[英]Adding a second item to a list seems to override the first element I added
So I'm trying to add 2 Item objects into a list by looping through it but somehow the 2nd item overrides the first one. 因此,我试图通过遍历列表将2个Item对象添加到列表中,但是以某种方式第二个对象将覆盖第一个。 Sorry it's been a while since I coded so I'm having a hard time figuring out what I did wrong as I expect that the name for these items are different. 抱歉,自从我编码以来已经有一段时间了,所以我很难弄清楚我做错了什么,因为我希望这些项目的名称不同。 :D :d
public static List<Item> buyList = new ArrayList<Item>();
int qty=2;
public static void buyItems(int qty)
{
for(int i=1; i<=qty; i++)
{
Item thisItem = new Item();
thisItem.setName(driver.findElement("//xpathOfName["+i+"]").getText()));
thisItem.setPrice(driver.findElement("//xpathOfPrice["+i+"]").getText()));
// System.out.println("this item is >>>>>>>>" +thisItem.getName());
buyList.add(thisItem);
// System.out.println("item at 0 is >>>>>>>>" +buyList.get(0).getName());
}
}
Before adding "thisItem" into the buyList, it prints the correct name. 在将“ thisItem”添加到buyList之前,它将打印正确的名称。 But the moment I print it outside the loop, it prints the 2nd item twice (the ones I commented out). 但是,当我在循环外打印它时,它会打印第二个项目两次(我注释掉的项目)。 I also tried by directly adding a new item with name and price as parameters but it still seems to overwrite the previously added item into the list. 我还尝试通过直接添加名称和价格为参数的新项目来尝试,但它似乎仍将以前添加的项目覆盖到列表中。
I tried to simplify the html code below: 我试图简化下面的html代码:
<ul>
<li id="item-1">
<div>
<h4>First Item</h4>
</div>
</li>
<li id="item-2">
<div>
<h4>Second Item</h4>
</div>
</li>
</ul>
As you have induced the loop and you want to access the element through an index , you need to replace the following lines: 引起循环并要通过索引访问元素时,需要替换以下行:
thisItem.setName(driver.findElement("//xpathOfName["+i+"]").getText()));
thisItem.setPrice(driver.findElement("//xpathOfPrice["+i+"]").getText()));
With: 附:
thisItem.setName(driver.findElements("//xpathOfName").get(i).getText()));
thisItem.setPrice(driver.findElements("//xpathOfPrice").get(i).getText()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.