遍历数组 - java [英] Iterating through array - java

查看:34
本文介绍了遍历数组 - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否最好为此有一个方法并将 Array 传递给该方法,或者每次我想检查一个数字是否在 中时都将其写出来数组.

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.

多次重复相同的代码没有任何好处.

There is no benefit to repeating identical code multiple times.

此外,如果您将逻辑放在一个方法中并且它发生了变化,您只需要在一个地方修改您的代码.

Also, if you place the logic in a method and it changes, you only need to modify your code in one place.

是否要使用第 3 方库是一个完全不同的决定.

Whether or not you want to use a 3rd party library is an entirely different decision.

这篇关于遍历数组 - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆