Java 将循环的内部高级转换为检查空值
我有类似的东西Java 将循环的内部高级转换为检查空值,java,for-loop,set,Java,For Loop,Set,我有类似的东西 Set<String> scene = myClass.getScene(); Set<String> time = myClass.getTime(); Set<String> possibleKey= new HashSet<String>(); for(String selectedTime: time){ for(String Selectedscene: scene) { String key = sel
Set<String> scene = myClass.getScene();
Set<String> time = myClass.getTime();
Set<String> possibleKey= new HashSet<String>();
for(String selectedTime: time){
for(String Selectedscene: scene) {
String key = selectedTime+selectedScene;
possibleKey.add(key)
}
}
Set scene=myClass.getScene();
设置时间=myClass.getTime();
Set possibleKey=new HashSet();
for(字符串选择时间:时间){
用于(字符串选择场景:场景){
字符串键=selectedTime+selectedScene;
可能键。添加(键)
}
}
这段代码假设场景和时间永远不会为空。现在,我需要对其进行转换,以便任何或两个参数(场景或时间)都可以为null。因此,如果时间为空,则应随场景生成密钥,如果场景为空,则应随时间生成密钥
请帮忙。我在这里感到困惑。在您的特定情况下,您可以通过使用带有单个空字符串的集合来代替
null
集合来实现您想要的结果:
Set<String> single = new HashSet<String>();
single.add("");
if (time == null) {
time = single;
}
if (scene == null) {
scene = single;
}
Set single=new HashSet();
单数。加上(“”);
if(time==null){
时间=单身;
}
如果(场景==null){
场景=单身;
}
只要您将
selectedTime
和selectedScene
连接起来,并且在它们之间没有分隔符,这将起作用。您到底想做什么;你能再分享一些代码吗?例如,String key=time+scene当time
和scene
是Set
s字符串时,code>没有意义。如果scene和time集包含null元素怎么办?这正是OP所关心的。是否有可能使其在将来处理其他元素(用于密钥生成)时具有通用性?我的意思是,如果将来我在时间和场景之外再添加一个元素会怎么样?@CKK OP在他的问题中非常具体,关于什么可以是null
-这是time
和scene
,而不是它们的元素。@Viksraj这在一般情况下不起作用,但在您的特定情况下,您可以使用单个元素解决方案。