通过循环访问数组 - java的
问题描述:
我在想,如果这是更好地为这个方法并通过阵列
来的方法或我要检查,如果一个号码每次写出来是阵列
。
I was wondering if it was better to have a method for this and pass the Array
to that method or to write it out every time I want to check if a number is in the array
.
例如:
public static boolean inArray(int[] array, int check) {
for (int i = 0; i < array.length; i++){
if (array[i] == check)
return true;
}
return false;
}
感谢您提前帮助!
答
您一定要封装这个逻辑到一个方法。
You should definitely encapsulate this logic into a method.
还有就是要重复相同的code多次没有任何好处。
There is no benefit to repeating identical code multiple times.
此外,如果您将逻辑的方法和它的变化,你只需要修改code在一个地方。
Also, if you place the logic in a method and it changes, you only need to modify your code in one place.
无论你是否希望使用第三方库是一个完全不同的决定。
Whether or not you want to use a 3rd party library is an entirely different decision.