How to use Interface I class of org.testng package

Best Testng code snippet using org.testng.Interface I

Run Testng automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package org.testng.remote.strprotocol;
2
3
4
5/**
6 * Interface replicating the <code>ISuiteListener</code> used for remote listeners.
7 *
8 * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>
9 * @see org.testng.ISuiteListener
10 */
11public interface IRemoteSuiteListener {
12  /**
13   * General information about the number of suites to be run.
14   * This is called once before all suites.
15   *
16   * @param genericMessage a message containing the number of suites that will be run
17   */
18  void onInitialization(GenericMessage genericMessage);
19
20  /**
21   * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)
22   *
23   * @param suiteMessage the suite message containing the description of the suite to be run.
24   */
25  void onStart(SuiteMessage suiteMessage);
26
27  /**
28   * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)
29   *
30   * @param suiteMessage the suite message containing infos about the finished suite.
31   */
32  void onFinish(SuiteMessage suiteMessage);
33}
34
Full Screen
copy
1import exceptions.InvalidStockSymbolException;
2import exceptions.StockTickerConnectionError;
3import org.testng.annotations.AfterMethod;
4import org.testng.annotations.BeforeMethod;
5
6
7import static org.mockito.Mockito.mock;
8import static org.mockito.Mockito.never;
9import static org.mockito.Mockito.times;
10import static org.mockito.Mockito.verify;
11import static org.mockito.Mockito.when;
12
13import org.mockito.Mock;
14import org.testng.annotations.AfterMethod;
15import org.testng.annotations.DataProvider;
16import org.testng.annotations.Test;
17
18import static org.testng.Assert.*;
19
20public class StockQuoteAnalyzerTest {
21    @Mock
22    private StockQuoteGeneratorInterface generatorMock;
23    @Mock
24    private StockTickerAudioInterface audioMock;
25
26    private StockQuoteAnalyzer analyzer;
27
28    @BeforeMethod
29    public void setUp() throws Exception {
30        generatorMock = mock(StockQuoteGeneratorInterface.class);
31        audioMock = mock(StockTickerAudioInterface.class);
32    }
33
34    @AfterMethod
35    public void tearDown() throws Exception {
36        generatorMock = null;
37        audioMock = null;
38    }
39
40    @Test(expectedExceptions = InvalidStockSymbolException.class)
41    public void constructorShouldThrowExceptionWhenSymbolIsInvalid() throws Exception {
42        analyzer = new StockQuoteAnalyzer("ZZZZZZZZZ", generatorMock, audioMock);
43    }
44}
Full Screen
copy
1package org.testng.internal;
2
3import java.util.List;
4import java.util.Set;
5
6import org.testng.IConfigurationListener;
7import org.testng.ITestListener;
8import org.testng.ITestNGMethod;
9import org.testng.ITestResult;
10import org.testng.xml.XmlTest;
11
12/**
13 * An interface defining the notification for @Test results and also
14 * \@Configuration results.
15 *
16 * @author <a href="mailto:cedric@beust.com">Cedric Beust</a>
17 * @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>
18 */
19public interface ITestResultNotifier {
20
21  Set<ITestResult> getPassedTests(ITestNGMethod tm);
22
23  Set<ITestResult> getFailedTests(ITestNGMethod tm);
24
25  Set<ITestResult> getSkippedTests(ITestNGMethod tm);
26
27  void addPassedTest(ITestNGMethod tm, ITestResult tr);
28
29  void addSkippedTest(ITestNGMethod tm, ITestResult tr);
30
31  void addFailedTest(ITestNGMethod tm, ITestResult tr);
32
33  void addFailedButWithinSuccessPercentageTest(ITestNGMethod tm, ITestResult tr);
34
35  void addInvokedMethod(InvokedMethod im);
36
37  XmlTest getTest();
38
39  List<ITestListener> getTestListeners();
40
41  List<IConfigurationListener> getConfigurationListeners();
42}
43
Full Screen
copy
1for(Object key: map.keySet()){
2   Object value= map.get(key);
3   //Do your stuff
4}
5
Full Screen
copy
1for(Object key: data.keySet()){
2  int value= data.get(key);
3}
4
Full Screen
copy
1Map<String, Integer> m = new HashMap<String, Integer>();
2
Full Screen
copy
1// ********** Using an iterator ****************
2Iterator<Entry<String, Integer>> me = m.entrySet().iterator();
3while(me.hasNext()){
4    Entry<String, Integer> pair = me.next();
5    System.out.println(pair.getKey() + ":" + pair.getValue());
6}
7
8// *********** Using foreach ************************
9for(Entry<String, Integer> me : m.entrySet()){
10    System.out.println(me.getKey() + " : " + me.getValue());
11}
12
13// *********** Using keySet *****************************
14for(String s : m.keySet()){
15    System.out.println(s + " : " + m.get(s));
16}
17
18// *********** Using keySet and iterator *****************
19Iterator<String> me = m.keySet().iterator();
20while(me.hasNext()){
21    String key = me.next();
22    System.out.println(key + " : " + m.get(key));
23}
24
Full Screen
copy
1           //Functional Oprations
2            Map<String, String> mapString = new HashMap<>();
3            mapString.entrySet().stream().map((entry) -> {
4                String mapKey = entry.getKey();
5                return entry;
6            }).forEach((entry) -> {
7                String mapValue = entry.getValue();
8            });
9
10            //Intrator
11            Map<String, String> mapString = new HashMap<>();
12            for (Iterator<Map.Entry<String, String>> it = mapString.entrySet().iterator(); it.hasNext();) {
13                Map.Entry<String, String> entry = it.next();
14                String mapKey = entry.getKey();
15                String mapValue = entry.getValue();
16            }
17
18            //Simple for loop
19            Map<String, String> mapString = new HashMap<>();
20            for (Map.Entry<String, String> entry : mapString.entrySet()) {
21                String mapKey = entry.getKey();
22                String mapValue = entry.getValue();
23
24            }
25
Full Screen
copy
1for (String key : phnMap.keySet()) {
2    System.out.println("Key: " + key + " Value: " + phnMap.get(key));
3}
4
Full Screen
copy
1phnMap.forEach((k,v) -> System.out.println("Key: " + k + " Value: " + v));
2
Full Screen
copy
1phnMap.forEach((k,v)->{
2    System.out.println("Key: " + k + " Value: " + v);
3    if("abc".equals(k)){
4        System.out.println("Hello abc");
5    }
6});
7
Full Screen
copy
1map.entrySet().forEach(entry -> System.out.println(entry.getValue()));
2
Full Screen
copy
1Map<Integer, Integer> map = new HashMap<Integer, Integer>();
2Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
3while (entries.hasNext()) {
4    Map.Entry<Integer, Integer> entry = entries.next();
5    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
6}
7
Full Screen
copy
1    Iterator iterator = map.entrySet().iterator();
2    while (iterator.hasNext()) {
3        Map.Entry element = (Map.Entry)it.next();
4        LOGGER.debug("Key: " + element.getKey());
5        LOGGER.debug("value: " + element.getValue());    
6    }
7
Full Screen
copy
1public class abcd{
2    public static void main(String[] args)
3    {
4       Map<Integer, String> testMap = new HashMap<Integer, String>();
5        testMap.put(10, "a");
6        testMap.put(20, "b");
7        testMap.put(30, "c");
8        testMap.put(40, "d");
9        for (Integer key:testMap.keySet()) {
10            String value=testMap.get(key);
11            System.out.println(value);
12        }
13    }
14}
15
Full Screen
copy
1public class abcd {
2    public static void main(String[] args)
3    {
4       Map<Integer, String> testMap = new HashMap<Integer, String>();
5        testMap.put(10, "a");
6        testMap.put(20, "b");
7        testMap.put(30, "c");
8        testMap.put(40, "d");
9        for (Entry<Integer, String> entry : testMap.entrySet()) {
10            Integer key=entry.getKey();
11            String value=entry.getValue();
12        }
13    }
14}
15
Full Screen
copy
1Map map = new HashMap();
2for (Map.Entry entry : ((Set<Map.Entry>) map.entrySet())) {
3    System.out.println(entry.getKey() + "/" + entry.getValue());
4}
5
Full Screen
copy
1map.entrySet().forEach(System.out::println);
2
Full Screen
copy
1map.forEach((k,v) -> { System.out.println(k + ":" + v); });
2
Full Screen
copy
1map.entrySet().forEach((e) -> {
2            System.out.println(e.getKey() + " : " + e.getValue());
3        });
4
Full Screen
copy
1map.entrySet()
2    .stream()
3    .filter(e-> e.getValue() > 5)
4    .forEach(System.out::println);
5
Full Screen
copy
1public class HMIteration {
2
3
4    public static void main(String[] args) {
5        Map<Object, Object> linkedHashMap = new LinkedHashMap<>();
6        Map<Object, Object> hashMap = new HashMap<>();
7
8        for (int i=10; i>=0; i--) {
9            linkedHashMap.put(i, i);
10            hashMap.put(i, i);
11        }
12
13        System.out.println("LinkedHashMap (1): ");
14        linkedHashMap.forEach((k,v) -> { System.out.print(k + " (#="+k.hashCode() + "):" + v + ", "); });
15
16        System.out.println("\nLinkedHashMap (2): ");
17
18        linkedHashMap.entrySet().forEach((e) -> {
19            System.out.print(e.getKey() + " : " + e.getValue() + ", ");
20        });
21
22
23        System.out.println("\n\nHashMap (1): ");
24        hashMap.forEach((k,v) -> { System.out.print(k + " (#:"+k.hashCode() + "):" + v + ", "); });
25
26        System.out.println("\nHashMap (2): ");
27
28        hashMap.entrySet().forEach((e) -> {
29            System.out.print(e.getKey() + " : " + e.getValue() + ", ");
30        });
31    }
32}
33
Full Screen
copy
1LinkedHashMap (1):
210 (#=10):10, 9 (#=9):9, 8 (#=8):8, 7 (#=7):7, 6 (#=6):6, 5 (#=5):5, 4 (#=4):4, 3 (#=3):3, 2 (#=2):2, 1 (#=1):1, 0 (#=0):0,
3LinkedHashMap (2):
410 : 10, 9 : 9, 8 : 8, 7 : 7, 6 : 6, 5 : 5, 4 : 4, 3 : 3, 2 : 2, 1 : 1, 0 : 0,
5HashMap (1):
60 (#:0):0, 1 (#:1):1, 2 (#:2):2, 3 (#:3):3, 4 (#:4):4, 5 (#:5):5, 6 (#:6):6, 7 (#:7):7, 8 (#:8):8, 9 (#:9):9, 10 (#:10):10,
7HashMap (2):
80 : 0, 1 : 1, 2 : 2, 3 : 3, 4 : 4, 5 : 5, 6 : 6, 7 : 7, 8 : 8, 9 : 9, 10 : 10,
9
Full Screen
copy
1for( Iterator entries = myMap.entrySet().iterator(); entries.hasNext();){
2
3  Entry entry = (Entry) entries.next();
4
5  System.out.println(entry.getKey() + "/" + entry.getValue());
6
7  //...
8}
9
Full Screen
copy
1//1.
2for (Map.Entry entry : hm.entrySet()) {
3    System.out.print("key,val: ");
4    System.out.println(entry.getKey() + "," + entry.getValue());
5}
6
7//2.
8Iterator iter = hm.keySet().iterator();
9while(iter.hasNext()) {
10    Integer key = (Integer)iter.next();
11    String val = (String)hm.get(key);
12    System.out.println("key,val: " + key + "," + val);
13}
14
15//3.
16Iterator it = hm.entrySet().iterator();
17while (it.hasNext()) {
18    Map.Entry entry = (Map.Entry) it.next();
19    Integer key = (Integer)entry.getKey();
20    String val = (String)entry.getValue();
21    System.out.println("key,val: " + key + "," + val);
22}
23
Full Screen
copy
1myMap.entrySet().stream().forEach((entry) -> {
2    Object currentKey = entry.getKey();
3    Object currentValue = entry.getValue();
4});
5
Full Screen
copy
1HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
2/*
3 *     Logic to put the Key,Value pair in your HashMap hm
4 */
5
6// Print the key value pair in one line.
7
8hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
9
10// Just copy and paste above line to your code.
11
Full Screen
copy
1HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
2    Random rand = new Random(47);
3    int i = 0;
4    while(i < 5) {
5        i++;
6        int key = rand.nextInt(20);
7        int value = rand.nextInt(50);
8        System.out.println("Inserting key: " + key + " Value: " + value);
9        Integer imap = hm.put(key, value);
10        if( imap == null) {
11            System.out.println("Inserted");
12        } else {
13            System.out.println("Replaced with " + imap);
14        }               
15    }
16
17    hm.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
18
19Output:
20
21Inserting key: 18 Value: 5
22Inserted
23Inserting key: 13 Value: 11
24Inserted
25Inserting key: 1 Value: 29
26Inserted
27Inserting key: 8 Value: 0
28Inserted
29Inserting key: 2 Value: 7
30Inserted
31key: 1 value:29
32key: 18 value:5
33key: 2 value:7
34key: 8 value:0
35key: 13 value:11
36
Full Screen
copy
1Spliterator sit = hm.entrySet().spliterator();
2
Full Screen
copy
1Map<String,String> sample = new HashMap<>();
2sample.put("A","Apple");
3sample.put("B", "Ball");
4
Full Screen
copy
1sample.keySet().forEach((k) -> System.out.println(k));
2
Full Screen
copy
1sample.values().forEach((v) -> System.out.println(v));
2
Full Screen
copy
1sample.forEach((k,v) -> System.out.println(k + ":" + v)); 
2sample.entrySet().stream().forEach((entry) -> {
3            Object currentKey = entry.getKey();
4            Object currentValue = entry.getValue();
5            System.out.println(currentKey + ":" + currentValue);
6        });
7
Full Screen
copy
1MutableBag<String> result = Bags.mutable.empty();
2MutableMap<Integer, String> map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three");
3map.forEachKeyValue((key, value) -> result.add(key + value));
4Assert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);
5
Full Screen
copy
1final MutableBag<String> result = Bags.mutable.empty();
2MutableMap<Integer, String> map = Maps.mutable.of(1, "One", 2, "Two", 3, "Three");
3map.forEachKeyValue(new Procedure2<Integer, String>()
4{
5    public void value(Integer key, String value)
6    {
7        result.add(key + value);
8    }
9});
10Assert.assertEquals(Bags.mutable.of("1One", "2Two", "3Three"), result);
11
Full Screen
copy
1map.forEach((k, v) -> System.out.println((k + ":" + v)));
2
Full Screen
copy
1for (String key: map.keySet()) {
2   System.out.println(key + "/" + map.get(key));
3}
4
Full Screen
copy
1for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
2    entry.getKey();
3    entry.getValue();
4}
5
Full Screen
copy
1for (String key : testMap.keySet()) {
2    testMap.get(key);
3}
4
Full Screen
copy
1Iterator<Map.Entry<String,Integer>> itr1 = testMap.entrySet().iterator();
2while(itr1.hasNext()) {
3    Map.Entry<String,Integer> entry = itr1.next();
4    entry.getKey();
5    entry.getValue();
6}
7
Full Screen
copy
1Iterator itr2 = testMap.keySet().iterator();
2while(itr2.hasNext()) {
3    String key = itr2.next();
4    testMap.get(key);
5}
6
Full Screen
copy
1Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();
2while (entries.hasNext()) {
3  Map.Entry<String, String> entry = entries.next();
4  String key = entry.getKey();
5  String value = entry.getValue();
6  // ...
7}
8
Full Screen
copy
1Map<String,Thing> map = ...;
2for (Map.Entry<String,Thing> entry : map.entrySet()) {
3    String key = entry.getKey();
4    Thing thing = entry.getValue();
5    ...
6}
7
Full Screen
copy
1Iterator entries = myMap.entrySet().iterator();
2while (entries.hasNext()) {
3  Entry thisEntry = (Entry) entries.next();
4  Object key = thisEntry.getKey();
5  Object value = thisEntry.getValue();
6  // ...
7}
8
Full Screen
copy
1 Map<String,String> map = new HashMap<>();
2 map.put("SomeKey", "SomeValue");
3 map.forEach( (k,v) -> [do something with key and value] );
4
5 // such as
6 map.forEach( (k,v) -> System.out.println("Key: " + k + ": Value: " + v));
7
Full Screen
copy
1          100     600      1100     1600     2100
2test10    0.333    1.631    2.752    5.937    8.024
3test3     0.309    1.971    4.147    8.147   10.473
4test6     0.372    2.190    4.470    8.322   10.531
5test1     0.405    2.237    4.616    8.645   10.707
6test2     0.376    2.267    4.809    8.403   10.910
7test7     0.473    2.448    5.668    9.790   12.125
8test9     0.565    2.830    5.952   13.220   16.965
9test4     0.808    5.012    8.813   13.939   17.407
10test5     0.810    5.104    8.533   14.064   17.422
11test8     5.173   12.499   17.351   24.671   30.403
12
Full Screen
copy
1Map<String, String> map = ...
2for (Map.Entry<String, String> entry : map.entrySet()) {
3    System.out.println(entry.getKey() + "/" + entry.getValue());
4}
5
Full Screen
copy
1for (var entry : map.entrySet()) {
2    System.out.println(entry.getKey() + "/" + entry.getValue());
3}
4
Full Screen
copy
1public static void main(String[] args) {
2    List<Long> times = new ArrayList<>();
3    for (int i = 0; i < 100; i++) {
4        times.add(doIt());
5    }
6    System.out.println("avg = " + (times.stream().mapToLong(x -> x).average()));
7}
8
9static long doIt() {
10    long start = System.nanoTime();
11    List<Object> list = new LinkedList<>();
12    //uncomment line below to test with ArrayList
13    //list = new ArrayList<>();
14    for (int i = 0; i < 500; i++) {
15        list.add(i);
16    }
17
18    Iterator it = list.iterator();
19    while (it.hasNext()) {
20        it.next();
21        it.remove();
22    }
23    long end = System.nanoTime();
24    long diff = end - start;
25    //uncomment to see the JVM warmup and get faster for the first few iterations
26    //System.out.println(diff)
27    return diff;
28}
29
Full Screen
copy
1get                 O(1)
2add                 O(1)
3contains            O(n)
4next                O(1)
5remove              O(n)
6iterator.remove     O(n)
7
Full Screen
copy
1get                 O(n)
2add                 O(1)
3contains            O(n)
4next                O(1)
5remove              O(1)
6iterator.remove     O(1)
7
Full Screen
copy
1get                 O(1)
2add                 O(n)
3contains            O(n)
4next                O(1)
5remove              O(n)
6iterator.remove     O(n)
7
Full Screen
copy
1|---------------------|---------------------|--------------------|------------|
2|      Operation      |     ArrayList       |     LinkedList     |   Winner   |
3|---------------------|---------------------|--------------------|------------|
4|     get(index)      |       O(1)          |         O(n)       | ArrayList  |
5|                     |                     |  n/4 steps in avg  |            |
6|---------------------|---------------------|--------------------|------------|
7|      add(E)         |       O(1)          |         O(1)       | LinkedList |
8|                     |---------------------|--------------------|            |
9|                     | O(n) in worst case  |                    |            |
10|---------------------|---------------------|--------------------|------------|
11|    add(index, E)    |       O(n)          |         O(n)       | LinkedList |
12|                     |     n/2 steps       |      n/4 steps     |            |
13|                     |---------------------|--------------------|            |
14|                     |                     |  O(1) if index = 0 |            |
15|---------------------|---------------------|--------------------|------------|
16|  remove(index, E)   |       O(n)          |         O(n)       | LinkedList |
17|                     |---------------------|--------------------|            |
18|                     |     n/2 steps       |      n/4 steps     |            |
19|---------------------|---------------------|--------------------|------------|
20|  Iterator.remove()  |       O(n)          |         O(1)       | LinkedList |
21|  ListIterator.add() |                     |                    |            |
22|---------------------|---------------------|--------------------|------------|
23
24
25|--------------------------------------|-----------------------------------|
26|              ArrayList               |            LinkedList             |
27|--------------------------------------|-----------------------------------|
28|     Allows fast read access          |   Retrieving element takes O(n)   |
29|--------------------------------------|-----------------------------------|
30|   Adding an element require shifting | o(1) [but traversing takes time]  |
31|       all the later elements         |                                   |
32|--------------------------------------|-----------------------------------|
33|   To add more elements than capacity |
34|    new array need to be allocated    |
35|--------------------------------------|
36
Full Screen
copy
1Latency Comparison Numbers (~2012)
2----------------------------------
3L1 cache reference                           0.5 ns
4Branch mispredict                            5   ns
5L2 cache reference                           7   ns                      14x L1 cache
6Mutex lock/unlock                           25   ns
7Main memory reference                      100   ns                      20x L2 cache, 200x L1 cache
8Compress 1K bytes with Zippy             3,000   ns        3 us
9Send 1K bytes over 1 Gbps network       10,000   ns       10 us
10Read 4K randomly from SSD*             150,000   ns      150 us          ~1GB/sec SSD
11Read 1 MB sequentially from memory     250,000   ns      250 us
12Round trip within same datacenter      500,000   ns      500 us
13Read 1 MB sequentially from SSD*     1,000,000   ns    1,000 us    1 ms  ~1GB/sec SSD, 4X memory
14Disk seek                           10,000,000   ns   10,000 us   10 ms  20x datacenter roundtrip
15Read 1 MB sequentially from disk    20,000,000   ns   20,000 us   20 ms  80x memory, 20X SSD
16Send packet CA->Netherlands->CA    150,000,000   ns  150,000 us  150 ms
17
Full Screen
copy
1Operation                       ArrayList                      LinkedList  
2
3AddAll   (Insert)               101,16719                      2623,29291 
4
5Add      (Insert-Sequentially)  152,46840                      966,62216
6
7Add      (insert-randomly)      36527                          29193
8
9remove   (Delete)               20,56,9095                     20,45,4904
10
11contains (Search)               186,15,704                     189,64,981
12
Full Screen
copy
1import org.junit.Assert;
2import org.junit.Test;
3
4import java.util.*;
5
6public class ArrayListVsLinkedList {
7    private static final int MAX = 500000;
8    String[] strings = maxArray();
9
10    ////////////// ADD ALL ////////////////////////////////////////
11    @Test
12    public void arrayListAddAll() {
13        Watch watch = new Watch();
14        List<String> stringList = Arrays.asList(strings);
15        List<String> arrayList = new ArrayList<String>(MAX);
16
17        watch.start();
18        arrayList.addAll(stringList);
19        watch.totalTime("Array List addAll() = ");//101,16719 Nanoseconds
20    }
21
22    @Test
23    public void linkedListAddAll() throws Exception {
24        Watch watch = new Watch();
25        List<String> stringList = Arrays.asList(strings);
26
27        watch.start();
28        List<String> linkedList = new LinkedList<String>();
29        linkedList.addAll(stringList);
30        watch.totalTime("Linked List addAll() = ");  //2623,29291 Nanoseconds
31    }
32
33    //Note: ArrayList is 26 time faster here than LinkedList for addAll()
34
35    ///////////////// INSERT /////////////////////////////////////////////
36    @Test
37    public void arrayListAdd() {
38        Watch watch = new Watch();
39        List<String> arrayList = new ArrayList<String>(MAX);
40
41        watch.start();
42        for (String string : strings)
43            arrayList.add(string);
44        watch.totalTime("Array List add() = ");//152,46840 Nanoseconds
45    }
46
47    @Test
48    public void linkedListAdd() {
49        Watch watch = new Watch();
50
51        List<String> linkedList = new LinkedList<String>();
52        watch.start();
53        for (String string : strings)
54            linkedList.add(string);
55        watch.totalTime("Linked List add() = ");  //966,62216 Nanoseconds
56    }
57
58    //Note: ArrayList is 9 times faster than LinkedList for add sequentially
59
60    /////////////////// INSERT IN BETWEEN ///////////////////////////////////////
61
62    @Test
63    public void arrayListInsertOne() {
64        Watch watch = new Watch();
65        List<String> stringList = Arrays.asList(strings);
66        List<String> arrayList = new ArrayList<String>(MAX + MAX / 10);
67        arrayList.addAll(stringList);
68
69        String insertString0 = getString(true, MAX / 2 + 10);
70        String insertString1 = getString(true, MAX / 2 + 20);
71        String insertString2 = getString(true, MAX / 2 + 30);
72        String insertString3 = getString(true, MAX / 2 + 40);
73
74        watch.start();
75
76        arrayList.add(insertString0);
77        arrayList.add(insertString1);
78        arrayList.add(insertString2);
79        arrayList.add(insertString3);
80
81        watch.totalTime("Array List add() = ");//36527
82    }
83
84    @Test
85    public void linkedListInsertOne() {
86        Watch watch = new Watch();
87        List<String> stringList = Arrays.asList(strings);
88        List<String> linkedList = new LinkedList<String>();
89        linkedList.addAll(stringList);
90
91        String insertString0 = getString(true, MAX / 2 + 10);
92        String insertString1 = getString(true, MAX / 2 + 20);
93        String insertString2 = getString(true, MAX / 2 + 30);
94        String insertString3 = getString(true, MAX / 2 + 40);
95
96        watch.start();
97
98        linkedList.add(insertString0);
99        linkedList.add(insertString1);
100        linkedList.add(insertString2);
101        linkedList.add(insertString3);
102
103        watch.totalTime("Linked List add = ");//29193
104    }
105
106
107    //Note: LinkedList is 3000 nanosecond faster than ArrayList for insert randomly.
108
109    ////////////////// DELETE //////////////////////////////////////////////////////
110    @Test
111    public void arrayListRemove() throws Exception {
112        Watch watch = new Watch();
113        List<String> stringList = Arrays.asList(strings);
114        List<String> arrayList = new ArrayList<String>(MAX);
115
116        arrayList.addAll(stringList);
117        String searchString0 = getString(true, MAX / 2 + 10);
118        String searchString1 = getString(true, MAX / 2 + 20);
119
120        watch.start();
121        arrayList.remove(searchString0);
122        arrayList.remove(searchString1);
123        watch.totalTime("Array List remove() = ");//20,56,9095 Nanoseconds
124    }
125
126    @Test
127    public void linkedListRemove() throws Exception {
128        Watch watch = new Watch();
129        List<String> linkedList = new LinkedList<String>();
130        linkedList.addAll(Arrays.asList(strings));
131
132        String searchString0 = getString(true, MAX / 2 + 10);
133        String searchString1 = getString(true, MAX / 2 + 20);
134
135        watch.start();
136        linkedList.remove(searchString0);
137        linkedList.remove(searchString1);
138        watch.totalTime("Linked List remove = ");//20,45,4904 Nanoseconds
139    }
140
141    //Note: LinkedList is 10 millisecond faster than ArrayList while removing item.
142
143    ///////////////////// SEARCH ///////////////////////////////////////////
144    @Test
145    public void arrayListSearch() throws Exception {
146        Watch watch = new Watch();
147        List<String> stringList = Arrays.asList(strings);
148        List<String> arrayList = new ArrayList<String>(MAX);
149
150        arrayList.addAll(stringList);
151        String searchString0 = getString(true, MAX / 2 + 10);
152        String searchString1 = getString(true, MAX / 2 + 20);
153
154        watch.start();
155        arrayList.contains(searchString0);
156        arrayList.contains(searchString1);
157        watch.totalTime("Array List addAll() time = ");//186,15,704
158    }
159
160    @Test
161    public void linkedListSearch() throws Exception {
162        Watch watch = new Watch();
163        List<String> linkedList = new LinkedList<String>();
164        linkedList.addAll(Arrays.asList(strings));
165
166        String searchString0 = getString(true, MAX / 2 + 10);
167        String searchString1 = getString(true, MAX / 2 + 20);
168
169        watch.start();
170        linkedList.contains(searchString0);
171        linkedList.contains(searchString1);
172        watch.totalTime("Linked List addAll() time = ");//189,64,981
173    }
174
175    //Note: Linked List is 500 Milliseconds faster than ArrayList
176
177    class Watch {
178        private long startTime;
179        private long endTime;
180
181        public void start() {
182            startTime = System.nanoTime();
183        }
184
185        private void stop() {
186            endTime = System.nanoTime();
187        }
188
189        public void totalTime(String s) {
190            stop();
191            System.out.println(s + (endTime - startTime));
192        }
193    }
194
195
196    private String[] maxArray() {
197        String[] strings = new String[MAX];
198        Boolean result = Boolean.TRUE;
199        for (int i = 0; i < MAX; i++) {
200            strings[i] = getString(result, i);
201            result = !result;
202        }
203        return strings;
204    }
205
206    private String getString(Boolean result, int i) {
207        return String.valueOf(result) + i + String.valueOf(!result);
208    }
209}
210
Full Screen
copy
1Algorithm           ArrayList   LinkedList
2seek front            O(1)         O(1)
3seek back             O(1)         O(1)
4seek to index         O(1)         O(N)
5insert at front       O(N)         O(1)
6insert at back        O(1)         O(1)
7insert after an item  O(N)         O(1)
8
Full Screen
copy
1type User struct {
2  Name string
3  Age int
4}
5
6var user User
7
8user.Name = "name"
9user.Age = 18
10
11var bytes, err = json.Marshal(user)
12
Full Screen
copy
1public class DataDog implements java.io.Serializable {
2
3private static final long serialVersionUID = -3774654564564563L;
4
5private int id;
6private String nameOfDog;
7
8// The constructor should NOT have arguments
9public DataDog () {}
10
11
12/** 4. getter/setter */
13
14// Getter(s)
15public int getId() {
16    return id;
17}
18
19public String getNameOfDog() {
20    return nameOfDog;
21}
22
23
24// Setter(s)
25public void setId(int id) {
26    this.id = id;
27}
28
29public void setNameOfDog(String nameOfDog) {
30    this.nameOfDog = nameOfDog;
31}}
32
Full Screen
copy
1/** 1. import java.io.Serializable */
2public class User implements java.io.Serializable {
3    /** 2. private fields */
4    private int id;
5    private String name;
6
7    /** 3. Constructor */
8    public User() {
9    }
10    public User(int id, String name) {
11        this.id = id;
12        this.name = name;
13    }
14
15    /** 4. getter/setter */
16    // getter
17    public int getId() {
18        return id;
19    }
20    public String getName() {
21        return name;
22    }
23    // setter
24    public void setId(int id) {
25        this.id = id;
26    }
27    public void setName(String name) {
28        this.name = name;
29    }
30}
31
Full Screen
copy
1@Entity
2public class Employee implements Serializable{
3
4   @Id
5   private int id;
6   private String name;   
7   private int salary;  
8
9   public Employee() {}
10
11   public Employee(String name, int salary) {
12      this.name = name;
13      this.salary = salary;
14   }
15   public int getId() {
16      return id;
17   }
18   public void setId( int id ) {
19      this.id = id;
20   }
21   public String getName() {
22      return name;
23   }
24   public void setName( String name ) {
25      this.name = name;
26   }
27   public int getSalary() {
28      return salary;
29   }
30   public void setSalary( int salary ) {
31      this.salary = salary;
32   }
33}
34
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)