Added function to print a list

This commit is contained in:
2021-06-30 16:52:31 -04:00
parent cebe376c1b
commit 8b8309199d
2 changed files with 41 additions and 0 deletions

View File

@@ -968,4 +968,16 @@ public class Algorithms{
//Conver the number to binary string
return num.toString(2);
}
//Print a list
public static <T> String printList(ArrayList<T> list){
StringBuilder listString = new StringBuilder("[");
for(int cnt = 0;cnt < list.size();++cnt){
listString.append(list.get(cnt));
if(cnt < list.size() - 1){
listString.append(", ");
}
}
listString.append("]");
return listString.toString();
}
}

View File

@@ -559,4 +559,33 @@ public class TestAlgorithms{
answer = Algorithms.toBin(bigNum);
assertEquals("toBin big 3 failed", correctAnswer, answer);
}
@Test
public void testPrintList(){
//Test 1
ArrayList<Integer> nums = new ArrayList<Integer>();
String correctAnswer = "[]";
String answer = Algorithms.printList(nums);
assertEquals("printList<Integer> 1 failed", correctAnswer, answer);
//Test 2
nums = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
correctAnswer = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]";
answer = Algorithms.printList(nums);
assertEquals("printList<Integer> 2 failed", correctAnswer, answer);
//Test 3
nums = new ArrayList<Integer>(Arrays.asList(-3, -2, -1, 0, 1, 2, 3));
correctAnswer = "[-3, -2, -1, 0, 1, 2, 3]";
answer = Algorithms.printList(nums);
assertEquals("printList<Integer> 3 failed", correctAnswer, answer);
//Test 4
ArrayList<String> strings = new ArrayList<String>(Arrays.asList("A", "B", "C"));
correctAnswer = "[A, B, C]";
answer = Algorithms.printList(strings);
assertEquals("printList<String> 1 failed", correctAnswer, answer);
//Test 5
strings = new ArrayList<String>(Arrays.asList("abc", "def", "ghi"));
correctAnswer = "[abc, def, ghi]";
answer = Algorithms.printList(strings);
assertEquals("printList<String> 2 failed", correctAnswer, answer);
}
}