java - 这在数组中如何工作?

标签 java arrays methods

你好,我在编写这段代码时遇到困难,我对最后两种方法感到困惑。这是一个学习练习(不是家庭作业),但我需要示例来学习。 另外,我认为这在 stackoverflow 数据库中也很有用。

public class NumberList {

public int[] values;  

public NumberList() {
    values = new int[0];
}

public NumberList(int[] a) {
values = new int [a.length];
for (int i=0;i<a.length;i++)
values[i] = a[i];
}

public int getSize() {
    return this.values.length;

}

public int getAt(int index) {
    if (index>=values.length){
        throw new IndexOutOfBoundsException ("Values of out of bounds");
    }else{
        return values[index];
    }
}

public long getTotal() {
    long sum = 0;
      for (int i=0; i<values.length; i++) {
        sum = sum + values[i];
      }
      return sum;



}
// need help here its a boolean that the number is in the array but if not its //false
public boolean contains(int number) {

     for (int i=0; i<values.length; i++){ 
        if (number <values.length+1){ 
            return true;

     }
     //else 
        // return false;
    // }


// this is an add method that confuses me and ask myself why since i added without it.
public void add(int number) {
     number=0;



}

}

最佳答案

public boolean contains(int number) {
     for (int i=0; i<values.length; i++) 
          if (number==values[i]) return true;
     return false;
}

public void add(int number) {
     int[] tmp = new int[value.length+1];
     for (int i=0; i<values.length; i++) tmp[i] = values[i];
     tmp[tmp.length-1] = number;
     values = tmp;
}

关于java - 这在数组中如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5587763/

相关文章:

java - Spring MVC 和 @RequestParam 与 x-www-form-urlencoded

java - 在java中对元组列表进行排序的有效方法

javascript - 在 JavaScript 中用一些空元素声明数组时发生了什么

c++ - 使用 C++ 在两个排序数组中查找匹配值索引的最有效方法

javascript - Zepto 通过 .data() 支持 data-* 属性

java - JAVA 中的 equals() 方法

ios - 切换 View 后, View 中仍然调用方法吗?

java - fragment 类中的View.findViewById

java - 自动隐藏任务栏和最大屏幕空间

python - 如何在类中的方法之间共享变量?