我有一堂课说大陆。我创建了许多这样的实例。我想将所有此类实例存储在Set中。每次创建新对象时,都应将其添加到集合中。
/**
* conditionalSum
* Runs a list of numbers against a custom conditional function and accumulators the values that passes
* @param {number[]} list
* @param {(n: number) => boolean} condition
* @returns {number}
*/
function conditionalSum(list, condition) {
var total = 0;
for (var index = 0; index < list.length; index++) {
var value = list[index];
if (condition(value)) {
total += value;
}
}
return total;
}
//TEST
function isEven(n) { return n % 2 === 0; }
function isOdd(n) { return n % 2 !== 0; }
console.log(conditionalSum([1, 2, 3, 4, 5], isEven));
console.log(conditionalSum([1, 2, 3, 4, 5], isOdd));
console.log(conditionalSum([13, 88, 12, 44, 99], isEven));
console.log(conditionalSum([], isOdd));
这给我一个物体泄漏的警告。我将使用多线程,因此,您对有效实现这种事情有什么建议吗?一个设计思路?
答案 0 :(得分:1)
您可以为您的大陆创建一个简单的工厂。
public class ContinentFactory {
private Set<Continent> continents = new HashSet<>();
public Continent create(String name) {
Continent continent = new Continent(name);
continents.add(continent);
return continent;
}
public static class Continent {
private String continentName;
public Continent(String continentName) {
this.continentName = continentName;
}
...
equals and hashcode
....
}
}
您也应该遵循Java命名约定: https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html
答案 1 :(得分:0)
Mabye更易于将Continent用作内部类:
public class Earth {
private static HashSet<Continent> globalContinents = new HashSet();
public Earth() {
}
public void addContinent(String name) {
globalContinents.add(new Continent(name));
}
private class Continent {
private String continent_name;
public Continent(String continent_name){
this.continent_name = continent_name;
}
public String getName() {
return this.continent_name;
}
}
}
因此,所有约束都在Earth的HashSet中,因此您只需创建一个Earth对象,然后使用addContinent()添加Coninents。