簡體   English   中英

如何創建自己的收藏集?

[英]How to create my own collection?

假設我有一個創建棒球卡的BaseballCard類。 現在,我需要創建另一個類,這將是我的收藏類。

例如,我將其稱為BaseballCardCollection

然后我想創建類似的方法

大小(返回集合中的卡數)

addCard(將棒球對象添加到收集對象)

removeCard(刪除棒球卡)

等等

什么是做到這一點的最佳方法。 我嘗試這樣做

public CardCollectionList() {
    BaseballCard[] baseballCardList = new BaseballCard[101];
 }

因此,每個對象都使用大小為100的BaseballCard類型的數組進行影射。

然后例如size方法,我嘗試了類似的方法

  public int size(){
    int size = 0;
    for(int i = 1; i<this.baseballCardList.length; i++)
        if (baseballCardList!= null)
            size+=1;

}

但這不起作用,因為“ baseballCardList無法解析為變量”

您可以嘗試使用ArrayList- http : //docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

ArrayList<baseballCard> baseballCardList = new ArrayList<baseballCard>(0);

public boolean addCard(baseballCard card){
    return baseballCardList.add(card);
}

public boolean removeCard(int card){
    return baseballCardList.remove(card);
}

public baseballCard getCard(int card){
    return baseballCardList.get(card);
}

public int sizeBaseballCardList(){
    return baseballCardList.size();
}

public ArrayList<baseballCard> getBaseballCardList(){
    return baseballCardList;
}

將變量BaseballCard[] baseballCardList移到構造函數之外,使其成為類中的一個字段。 做類似的size

這是該類的外觀:

public class CardCollectionList {
    //fields
    private BaseballCard[] baseballCardList;
    private int size;

    //constructor
    public CardCollectionList() {
         baseballCardList = new BaseballCard[101];
    }
    //method
    public int getSize() {
        return this.size;
    }
}

您可以嘗試創建自己的實現Collection接口的類,並定義自己的方法+實現Collection方法:

public class myContainer implements Collection <BaseballCard> {

}

您需要將變量聲明從構造函數移至類,以便也可以通過其他方法訪問它。

class CardCollectionList {
  BaseballCard[] baseballCardList;

  public CardCollectionList() {
    baseballCardList = new BaseballCard[101];
  }

  public int size(){
    int size = 0;
    for(int i = 1; i<this.baseballCardList.length; i++) {
      if (baseballCardList[i] != null) {
        size+=1;
      }
    }
    return size;
  }
}

該代碼盡可能接近您的片段。 有幾種方法可以改善此情況(添加時保持大小跟蹤,自動數組重新分配等)。 但這是一個開始,如果您想自己嘗試。

通常,您可能只使用ArrayList<BaseballCard>

現在,我需要創建另一個類,這將是我的收藏類。 ...這樣做的最佳方法是什么。

我沒有足夠的聲譽來評論您的問題,所以我假設您只想將BaseballCard對象存儲在Java Collection中 Java SDK提供了很多選項。 由於您詢問的是“最佳”方法,因此除非您需要添加其他功能,否則我將使用其中的一種。

如果您沒有從Java SDK中找到所需的東西,或者只是想創建自己的Collection,請遵循上面@michał-szydłowski給出的建議

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM