java - Java/selenium : list.clear(); clearing the result that i was trying to store in map before clearing the list
问题描述
I Was trying to store country and state values in map with key-value pair every time I loop through one country and get the list of states, I am trying to store them in Map and clearing the list upon selecting other countries but list.clear(); clearing the result that I have already stored in the map as well. please guide me here.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class DropdownTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Java\\Automation\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://frontendscript.com/demo/country-dropdown-list-javascript/");
WebElement country = driver.findElement(By.id("country"));
Select country_sel = new Select(country);
List<WebElement> countries = country_sel.getOptions();
WebElement state = driver.findElement(By.id("state"));
Select state_sel = new Select(state);
Map<String, List<String>> result = new HashMap<String, List<String>>();
List<String> state_names = new ArrayList<String>();
for (WebElement c : countries) {
if(!(c.getText().equalsIgnoreCase("Select Country"))) {
c.click();
List<WebElement> states = state_sel.getOptions();
for (WebElement s : states) {
if(!(s.getText().equalsIgnoreCase("Select State"))) {
//System.out.println(s.getText());
state_names.add(s.getText());
}
}
//System.out.println(state_names);
result.put(c.getText(), state_names);
state_names.clear();
System.out.println(result);
}}
}
}
解决方案
当您将列表作为值稍后映射和清除列表时,它实际上是指同一个对象。所以清除列表也会影响地图值中的元素。
所以正确的方法是List<String> state_names
在for
循环内创建。
更新代码:
Map<String, List<String>> result = new HashMap<String, List<String>>();
for (WebElement c : countries) {
if(!(c.getText().equalsIgnoreCase("Select Country"))) {
List<String> state_names = new ArrayList<String>(); // Inside the loop
c.click();
List<WebElement> states = state_sel.getOptions();
for (WebElement s : states) {
if(!(s.getText().equalsIgnoreCase("Select State"))) {
state_names.add(s.getText());
}
}
result.put(c.getText(), state_names);
System.out.println(result);
}}
推荐阅读
- c# - EF Core 写入操作与映射实体的问题
- java - synchronized关键字的Java多线程用途
- web-scraping - 使用 IMPORTXML 和 IMPORTHTML 混淆输出
- python-3.x - 如何找到值的所有键?
- dynamics-crm - 业务规则:添加其他字段值到日期?
- python - Python:如何从文本文件中拆分位置数据
- aries - 在使用 Indy 的 SSI 中,验证者如何选择证明请求的模式?
- django - Django:导入遗留数据库数据,保持具有自动键的主键
- java - java中的递增顺序
- jupyter - 自动保存 jupyter 工作区