Java 我想使用for循环来关闭一些方法
我想用for循环结束一些重复的语句 我的发言如下:Java 我想使用for循环来关闭一些方法,java,for-loop,Java,For Loop,我想用for循环结束一些重复的语句 我的发言如下: st1.close(); st2.close(); st3.close(); st4.close(); st5.close(); public static void close(Closeable... closeables) { try { for(Closeable c : closeables) c.close(); } catch(IOException e)
st1.close();
st2.close();
st3.close();
st4.close();
st5.close();
public static void close(Closeable... closeables)
{
try
{
for(Closeable c : closeables)
c.close();
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
close(st1, st2, st3, st4, st5);
我想用这样的方法来结束它们的循环:
for (int i = 1; i<6; i++) {
st(x).close();
}
for(int i=1;i您可以使用arraylist添加所有对象并对其进行迭代。例如:
List<YourClass> myList = new ArrayList<YourClass>();
// add objects of your class to this list
myList.add(st1);
myList.add(st2); // etc..
// iterate over the list
for (YourClass obj : myList) {
obj.close();
}
List myList=new ArrayList();
//将类的对象添加到此列表中
myList.add(st1);
myList.add(st2);//等等。。
//反复浏览列表
for(YourClass对象:myList){
obj.close();
}
您可以编写如下实用程序方法:
st1.close();
st2.close();
st3.close();
st4.close();
st5.close();
public static void close(Closeable... closeables)
{
try
{
for(Closeable c : closeables)
c.close();
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
close(st1, st2, st3, st4, st5);
这样称呼它:
st1.close();
st2.close();
st3.close();
st4.close();
st5.close();
public static void close(Closeable... closeables)
{
try
{
for(Closeable c : closeables)
c.close();
}
catch(IOException e)
{
throw new RuntimeException(e);
}
}
close(st1, st2, st3, st4, st5);
您可以使用数组/列表,然后对其进行迭代。当第一个数组抛出错误时会发生什么?应该发生什么?类似于?list.of(st1,st2).forEach(YourClass::close);
这过度简化了问题-确保在所有情况下调用thingsclose()
,并且没有错误“丢失”。。。