-
-
Notifications
You must be signed in to change notification settings - Fork 690
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix generics in flatten array (#2900)
The previous method signature didn't make sense because the tests were always giving a list of mixed objects. So, the method parameter could only take a List of mixed objects (i.e. T can only be an `Object`). This would have also meant that the method can only return a List of objects. Fixes #2896
- Loading branch information
1 parent
d53f6ab
commit 406af2a
Showing
3 changed files
with
11 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ | |
"aadityakulkarni", | ||
"FridaTveit", | ||
"jackattack24", | ||
"jagdish-15", | ||
"jmrunkle", | ||
"jtigger", | ||
"kytrinyx", | ||
|
29 changes: 9 additions & 20 deletions
29
exercises/practice/flatten-array/.meta/src/reference/java/Flattener.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,28 +1,17 @@ | ||
import java.util.ArrayList; | ||
import java.util.Collections; | ||
import java.util.List; | ||
|
||
final class Flattener { | ||
class Flattener { | ||
|
||
List flatten(final List nestedList) { | ||
if (nestedList.isEmpty()) { | ||
return new ArrayList<>(); | ||
} else { | ||
final List result = new ArrayList(); | ||
|
||
final Object head = nestedList.get(0); | ||
final List tail = nestedList.subList(1, nestedList.size()); | ||
|
||
if (head instanceof List) { | ||
result.addAll(flatten((List) head)); | ||
} else { | ||
result.add(head); | ||
List<Object> flatten(List<?> list) { | ||
List<Object> flattenedList = new ArrayList<>(); | ||
for (Object element: list) { | ||
if (element instanceof List<?> listAsElement) { | ||
flattenedList.addAll(flatten(listAsElement)); | ||
} else if (element != null) { | ||
flattenedList.add(element); | ||
} | ||
|
||
result.addAll(flatten(tail)); | ||
result.removeAll(Collections.singleton(null)); | ||
return result; | ||
} | ||
return flattenedList; | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters