英文:
Is there a way to reuse a part of code to instantiate array-lists that hold different data types?
问题
以下是翻译好的部分:
我想要找到一种在我的Java代码中重用类似数组列表的方法。使每个数组列表不同的唯一因素是它们所容纳的数据类型。特别是在我的程序中,我有一个名为ActionDeck
的类,它有一个实例变量数组列表,其中存储着对象ActionCard
;还有另一个名为SalaryDeck
的类,它有一个实例变量数组列表,其中存储着对象SalaryCard
。这两个类都有相同的实例变量和方法。是否有一种方法,我可以拥有某种蓝图,在代码的一部分中实例化这两个Deck类,但它所持有的对象是不同的?它继承自的抽象Deck
类仅具有相似的方法。我只是想要缩短代码量,因为我正在为其他牌组类重复这些代码,而且这似乎也是多余的。
public class SalaryDeck extends Deck {
private Deque<SalaryCard> salaryDeck;
private ArrayList<SalaryCard> temp;
public SalaryDeck () {
salaryDeck = new ArrayDeque<SalaryCard>();
temp = new ArrayList<SalaryCard>();
}
public class ActionDeck extends Deck {
// 用于动作卡牌组的实例变量
private Deque<ActionCard> actionDeck;
private ArrayList<ActionCard> temp;
/**
* 动作卡牌组对象的构造函数。它创建一个临时数组列表,以及一个用于将动作卡对象推入的双端队列。
*/
public ActionDeck() {
actionDeck = new ArrayDeque<ActionCard>();
temp = new ArrayList<ActionCard>();
}
我一直在考虑是否可以使用一个抽象类,但我不确定如何实现它。
非常感谢!
英文:
I wanted to find a way of reusing similar array lists in my code in Java. The only thing that makes each one different is the data type they hold. Particularly in my program I have a class ActionDeck
that has an instance variable array list of object ActionCard
and another class SalaryDeck
that has an instance variable array list of object SalaryCard
. Both of these classes have the same instance variables and methods. Is there a way I am able to have some kind of blueprint wherein I can just instantiate both Deck classes from one part of code but the object it holds is different? The abstract Deck
class it extends from holds similar methods only. I just want to shorten the amount of code since I'm repeating these for other deck classes and it seems redundant too.
public class SalaryDeck extends Deck {
private Deque<SalaryCard> salaryDeck;
private ArrayList<SalaryCard> temp;
public SalaryDeck () {
salaryDeck = new ArrayDeque<SalaryCard>();
temp = new ArrayList<SalaryCard>();
}
public class ActionDeck extends Deck {
// Instance variables for an action card deck
private Deque<ActionCard> actionDeck;
private ArrayList<ActionCard> temp;
/**
* Constructor for an action card deck object. It creates a temporary
* array list, as well as a deque for pushing action card objects into.
*/
public ActionDeck() {
actionDeck = new ArrayDeque<ActionCard>();
temp = new ArrayList<ActionCard>();
}
I kept thinking I could use an abstract class but I'm not sure of how to implement it.
Thank you very much!
答案1
得分: 2
你使你的Deck
类变成了泛型:
public abstract class Deck<C> {
protected final Deque<C> cards = new Deque<>();
}
public class ActionDeck extends Deck<ActionCard> {
}
英文:
You make your Deck
class generic:
public abstract class Deck<C> {
protected final Deque<C> cards = new Deque<>();
}
public class ActionDeck extends Deck<ActionCard> {
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论