簡體   English   中英

Java實例方法

[英]Java instance method

我有以下課程:

public class Example(

   private String id;
   private ArrayList<String> docs = new ArrayList();

   public Example(string startid){
      id = startid;
      docs = null;
   }

   public void myMethod(String externalID){

      Example myExample = new Example(externalID);

}

如果我在調用myMethod時理解得很好,它將創建一個名為myExample的Example實例,其id = externalID和docs = null。

我希望這個類做的是:從創建實例(myExample)的外部點同時調用myMethod並確保外部調用不能覆蓋任何myExample的變量(線程安全嗎?)我還希望它做的是從相應myExample實例中的外部調用填充docs數組。 這是可能的還是我必須同時使用startid傳遞ArrayList?

你理解不正確。

為了調用myMethod你需要有一個Example實例,調用myMethod將使用externalId實例化一個新實例,然后立即丟棄它。

根據我的理解你想要的是以下內容:

public class Example {

  // Final so it can't be modified once set.
  private final String id;

  // Final so it can't be switch to a different list.
  // Public so others can add to it and have acces to List methods.
  // Synchronized so acces to it from multiple threads is possible.
  // Note: You should probably make this private and have a getList() method that
  //       returns this instance to have nice encapsulation.
  public final List<String> docs = Collections.synchronizedList(new ArrayList());

  // Make default constructor private to force setting the startId.
  private Example() {}

  public Example(final String startId){
     this.id = startId;
  }
}

根據Benoit對你想要實現的想法,我認為最好的方法是使用Map(如果你想要線程安全的話,使用ConcurrentMap):

ConcurrentMap<String, List<String>> myData = new ConcurrentHashMap<>();

這樣,您可以按您提供的ID來處理任何列表。

List<String> myList = myData.get(id);

如果要限制列表的訪問者(例如,僅提供add方法),則需要將列表封裝在類中:

public final class Example {
    private final List<String> docs = new ArrayList<>();

    public boolean addDoc(final String doc) {
        return docs.add(doc);
    }
}

然后使用Map如下:

ConcurrentMap<String, Example> myData = new ConcurrentHashMap<>();

並添加這樣的文檔:

myData.get(id).addDoc(myDoc);

希望這可以幫助...

關於評論中討論的主題:設置變量

你有這樣一個類:

public class Example {
    public String var;
}

還有一個像這樣的例子

Example ex = new Example();

您可以使用設置值

ex.var = "abc";

像這樣的calss

public class Example {
    private String var;
    public void setVar(String var) {
        this.var = var;
    }
}

采用

ex.setVar("abc");

管理多個實例:

1)您的網絡服務獲取帶有ID的信息

2)您的服務器應用程序存儲實例映射,您可以通過ID訪問它(請參閱上面的映射示例)。 在您調用的Web服務中

Example ex = ReportHolder.getReport(id);

假設這樣一個類:

public class ReportHolder {
    private static ConcurrentMap<String, Example> map = new ConcurrentMap<>();
    public static Example getReport(final String id) {
        return map.get(id);
    }
}

3)然后你可以操縱實例。

確保正確理解變量,類,實例和靜態術語。 其他我很難理解你的錯誤發生的原因。

暫無
暫無

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

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