java - 移动和删除 ArrayList 条目

标签 java arraylist static

我正在使用桩。在我的例子中,堆是包含卡片数组列表的对象。我将使用其中 1 个以上,每个的用途都不同。

<小时/>

我在这里想做的是制作两种方法:

getCards:将对象引用从一个 Pile 移动到另一个 Pile

removeCards:删除多个数组列表条目

import java.util.ArrayList;

public abstract class Pile {

public static ArrayList <Card> newPile;

public Pile() {
    newPile = new ArrayList <Card>();
}


public abstract void displayPile(); 

public void removeCards(int numOfCards) {
    for (int i = 0; i < numOfCards; i++) {
        Pile.newPile.remove(0);
    }
}

public static void getCards(int numOfCards, Pile fromPile) {
    for (int i = 0; i < numOfCards; i++) {
        Pile.newPile.add(i, fromPile.newPile.get(i));             // here is the error
    }
}

}

错误是:

The static field Pile.newPile should be accessed in a static way.

<小时/>

有人愿意解释我做错了什么以及我该如何处理它吗?

最佳答案

静态成员变量由它们所属类的所有实例共享。由于 newPhile 是静态的,因此您无需在每个单独的对象中编辑它:

enter image description here (http://itcareerworld.com/wp-content/uploads/2015/02/static-keyword-diagram-1.png)

因为它是静态的,所以只有一份副本。要么从变量和方法中删除静态,要么不创建要实例化的对象,因为它已经在对象之间共享。我建议第一个。

我注意到你的评论,你说:

cannot make a static reference to the non-static field Pile.newPile

如果您执行该选项,只需将所有内容设为非静态(变量和方法)即可。

关于java - 移动和删除 ArrayList 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34012124/

相关文章:

java - 在二维 ArrayList 中添加元素

c# - 从泛型类型调用静态方法

java - 无法访问另一个类的方法

java - 文本文件的最后一行未正确存储到二维数组中

java - java.util.Arrays.asList(T...) 是如何工作的?

java - 使用迭代器从 List 中获取数据

Java 有 FindBugs。 Ruby 的等价物是什么?

java - 数量/Axis : how to force an immediate update of internal state during layout?

java - 通过Java登录网站?

java - DrawerLayout空指针异常