面向 SDET 和自动化测试工程师的 JAVA Collections

2024-09-01   出处: Medium  作/译者:Japneet Sachdeva/暖阳

Collection框架是用于表示和操作collections的统一架构。

Collection框架的层次结构

java.util 包包含 Collection 框架的所有类和接口。

Collection接口被分为以下2组:

最基本的接口是:java.util.collection

QA自动化的常用实现

Java Collections框架提供了几个核心接口的通用实现:

  • 对于List接口来说,ArrayList是最常用的实现。
  • 对于Set接口来说,HashSet是最常用的实现。
  • 对于Map接口来说,HashMap是最常用的实现。

ArrayList

ArrayList 类是一个可调整大小的数组,可以在 java.util 包中找到。

关于Java ArrayList类,以下是一些关键点:

  • Java ArrayList 类可以包含重复元素。
  • Java ArrayList类保持插入顺序。
  • Java ArrayList类是非同步的。
  • Java ArrayList 允许随机访问,因为数组基于索引工作。
  • 在Java ArrayList类中,如果从数组列表中移除任何元素,由于需要进行大量的移动操作,因此操作速度较慢。

创建 ArrayList 并添加元素

下面的示例演示了如何使用 ArrayList() 构造函数创建 ArrayList ,并使用 add() 方法向 ArrayList 中添加元素

    import java.util.ArrayList;
    import java.util.List;
    // How to create an ArrayList using the ArrayList() constructor.
    // Add new elements to an ArrayList using the add() method.
    public class CreateArrayListExample
    {
        public static void main(String[] args)
        {
            // Creating an ArrayList of String using
            List < String > fruits = new ArrayList < > ();
            // Adding new elements to the ArrayList
            fruits.add(“Banana”);
            fruits.add(“Apple”);
            fruits.add(“mango”);
            fruits.add(“orange”);
            System.out.println(fruits);
        }
    }

Output: [Banana, Apple, mango, orange]

如何获得同步版本的 ArrayList?

答:在Public static List synchronizedList(List l) Collections类中包含synchronizedList()方法。

例:

    ArrayList l = new ArrayList(); 
    List l2 = Collections.synchronizedList(l);

同样,我们可以通过以下方法获取Set和Map对象的同步版本。

    Public static List synchronizedSet(Set s)
    Public static List synchronizedMap(Map m)

HashSET

Set 是一个不能包含重复元素的集合。它是数学集合抽象的建模。

排序:

Set 中的元素可以使用 TreeSet 实现类按升序排序。HashSet 实现类不提供排序保证。LinkedHashSet 实现类保持插入顺序。

Null 元素:

所有Set实现最多允许一个null元素。

不支持下标访问:

与List接口不同,Set接口不提供任何通过索引访问元素的方法,因为Set不保持任何固定的顺序。

HashSet中的方法

add()

add()方法可用于将元素添加到集合中。该方法契约规定,只有当元素尚未出现在集合中时,才会添加该元素。如果成功添加了元素,该方法返回 true,否则返回 false。

我们可以像这样在 HashSet 中添加一个元素:

    @Test
    public void whenAddingElement_shouldAddElement()
        {
            Set < String > hashset = new HashSet < > ();
            assertTrue(hashset.add(“String Added”));
        }
contains()

contains 方法的目的是检查一个元素是否存在于给定的 HashSet 中。如果找到该元素则返回 true,否则返回 false。

我们可以这样在HashSet中检查元素:

    @Test
    public void whenCheckingForElement_shouldSearchForElement()
    {
        Set < String > hashsetContains = new HashSet < > ();
        hashsetContains.add(“String Added”);
        assertTrue(hashsetContains.contains(“String Added”));
    }

将HashSet与Selenium WebDriver结合使用

    public class SeleniumHashSetExample
    {
        public static void main(String[] args)
        {
            // Set the path to chromedriver executable
            System.setProperty("webdriver.chrome.driver", "path / to / chromedriver");
            // Initialize ChromeDriver
            WebDriver driver = new ChromeDriver();
            // Navigate to the webpage
            driver.get("https: //example.com");
            // Find all links on the webpage
            List < WebElement > links = driver.findElements(By.tagName("a"));
            // Create a HashSet to store unique links
            Set < String > uniqueLinks = new HashSet < > ();
            // Iterate through the list of links
            for(WebElement link: links)
            {
                // Get the href attribute of the link
                String href = link.getAttribute("href");
                // Add the link to the HashSet
                uniqueLinks.add(href);
            }
            // Print the unique links
            System.out.println("Unique Links: ");
            for(String link: uniqueLinks)
            {
                System.out.println(link);
            }
            // Close the browser
            driver.quit();
            }
        }

HashMap

map是一种键值映射结构,这意味着每个键都映射到一个值,我们可以使用键从map中检索相应的值。

创建HashMap

在 HashMap 中添加元素,需要提供 2 个东西,key和value。

key:与指定值关联的键。允许为空。

value:与指定键关联的值。

例如:

    import java.util.Map;
    class Hashmap_Java
    {
        public static void main(String args[])
        {
            HashMap < Integer, String > map = new HashMap < Integer, String > ();
            map.put(100, “Mumbai”);
            map.put(101, “Delhi”);
            map.put(102, “Pune”);
            // Add Element
            map.put(103, “Surat”);
            // Size of map
            System.out.println(map.size());
            // clears hashmap , removes all element
            map.clear();
            // Checking if HashMap is empty
            System.out.println("Is HashMap is empty: "+map.isEmpty());
            for(Map.Entry m: map.entrySet())
            {
                System.out.println(m.getKey() + " " +m.getValue());
            }
        }
    }

Output:

4

Is HashMap is empty: true

使用Map.Entry和Map.entrySet

我们经常使用来存储键值对的集合。 在某些时候,我们经常需要对它们进行迭代。

假设我们有一个以作者姓名为键,书名为值的map:

    Map < String, String > map = new HashMap < > ();
    map.put("Robert C.Martin", "Clean Code");
    map.put("Joshua Bloch", "Effective Java");
    for(Map.Entry < String, String > book: bookMap.entrySet())
    {
         System.out.println("key: "+book.getKey() + "value: "+book.getValue());
    }

在这个例子中,我们的循环遍历了一个Map.Entry对象的集合。由于Map.Entry在一个类中同时存储键和值,我们可以通过一次操作同时获取它们。

这些只是理解Collections框架深度和功能的基础知识。

如果您想更深入地了解 JAVA 和数据结构中的Collections,请查看我的电子书:Learn to Code in Java and Crack Coding Rounds


声明:本文为本站编辑转载,文章版权归原作者所有。文章内容为作者个人观点,本站只提供转载参考(依行业惯例严格标明出处和作译者),目的在于传递更多专业信息,普惠测试相关从业者,开源分享,推动行业交流和进步。 如涉及作品内容、版权和其它问题,请原作者及时与本站联系(QQ:1017718740),我们将第一时间进行处理。本站拥有对此声明的最终解释权!欢迎大家通过新浪微博(@测试窝)或微信公众号(测试窝)关注我们,与我们的编辑和其他窝友交流。
129° /1298 人阅读/0 条评论 发表评论

登录 后发表评论