title: Using WeakReferences in Java
body: <p>I have been trying to use <code>WeakReference</code> in my Android projects and I have never had any success. Now I really need it as I am dealing with old devices and I have to keep the memory clean as much as I can.</p>
  
  <p>Anyway, I have an array which has about 1000 list of different strings in it. I need to load it then find a string in it.</p>
  
  <p>This is how I am currently using it:</p>
  
  <pre><code>String[] campaignList = context.getResources().getStringArray(R.array.campaignList);
  WeakReference&lt;String[]&gt; weakCampaignList = new WeakReference&lt;String[]&gt;(campaignList);
  </code></pre>
  
  <p>Is this the correct way of using <code>WeakReference</code>? 
  If yes then what I don't understand is the array is getting hydrated at <code>String[]</code> and then I pass it to the <code>WeakReference</code>. So doesn't this mean I have 2 spots on the memory allocated to one array? Or I am completely misunderstanding the <code>WeakReference</code> concept?</p>
  
  <p>A very good resource that I found among all the resources is this one:</p>
  
  <p><a href="http://neverfear.org/blog/view/150/Strong_Soft_Weak_and_Phantom_References_Java" rel="nofollow">http://neverfear.org/blog/view/150/Strong_Soft_Weak_and_Phantom_References_Java</a></p>
  
  <p>Edit:</p>
  
  <p>My code works with no issue. Just need to know if I am doing it correct in terms of performance.</p>
  
  <pre><code>for (int i = 0; i &lt; weakCampaignList.get().length; i++) {
    Log.d(TAG,"weakCampaignList: "+weakCampaignList.get()[i]);
  }
  </code></pre>
  
  <p>My Entire Method</p>
  
  <pre><code>public static String getTheCampaign(String country, Context context) {
          String campaign = "";
          campaign = "annual_subscription_" + country;
  
          String[] campaignList = context.getResources().getStringArray(
                  R.array.campaign_list);
  
          ArrayList&lt;WeakReference&lt;String&gt;&gt; weakCampaignList = new ArrayList&lt;WeakReference&lt;String&gt;&gt;();
          for (String s : campaignList) {
              weakCampaignList.add(new WeakReference&lt;String&gt;(s));
          }
  
          if (country.equals("") || country.isEmpty()) {
              campaign = "annual_subscription_us";
          } else {
              for (int i = 0; i &lt; weakCampaignList.size(); i++) {
                  if (weakCampaignList.get(i).get().contains(campaign)) {
                      campaign = weakCampaignList.get(i).get();
                      return campaign;
                  } 
              }
          }
          return campaign;
      }
  </code></pre>