1 19 20 package org.openide.util; 21 22 import java.beans.PropertyChangeListener ; 23 import java.lang.ref.WeakReference ; 24 import java.lang.reflect.Method ; 25 import java.util.Arrays ; 26 import java.util.Iterator ; 27 import java.util.Vector ; 28 import junit.framework.*; 29 import org.netbeans.junit.*; 30 31 public class WeakSetTest extends NbTestCase { 32 33 public WeakSetTest(java.lang.String testName) { 34 super(testName); 35 } 36 37 public static void main(java.lang.String [] args) { 38 junit.textui.TestRunner.run(new NbTestSuite(WeakSetTest.class)); 39 } 40 41 public void testToArrayMayContainNullsIssue42271 () { 42 class R implements Runnable { 43 Object [] arr; 44 Object last; 45 46 public R () { 47 int cnt = 10; 48 arr = new Object [cnt]; 49 for (int i = 0; i < cnt; i++) { 50 arr[i] = new Integer (i); 51 } 52 } 53 54 55 public void run () { 56 57 WeakReference r = new WeakReference (last); 58 for (int i = 0; i < arr.length; i++) { 59 arr[i] = null; 60 } 61 arr = null; 62 last = null; 63 assertGC ("Last item has to disappear", r); 64 } 65 66 public void putToSet (NotifyWhenIteratedSet s) { 67 for (int i = 0; i < arr.length; i++) { 68 s.add (arr[i]); 69 } 70 assertEquals (arr.length, s.size ()); 71 Iterator it = s.superIterator (); 72 Object prev = it.next (); 73 while (it.hasNext ()) { 74 prev = it.next (); 75 } 76 last = prev; 77 } 78 } 79 R r = new R (); 80 81 82 83 NotifyWhenIteratedSet ws = new NotifyWhenIteratedSet (r, 1); 84 85 r.putToSet (ws); 86 87 Object [] arr = ws.toArray (); 88 for (int i = 0; i < arr.length; i++) { 89 assertNotNull (i + "th index should not be null", arr[i]); 90 } 91 } 92 93 private static final class NotifyWhenIteratedSet extends WeakSet { 94 private Runnable run; 95 private int cnt; 96 97 public NotifyWhenIteratedSet (Runnable run, int cnt) { 98 this.run = run; 99 this.cnt = cnt; 100 } 101 102 public Iterator superIterator () { 103 return super.iterator (); 104 } 105 106 public Iterator iterator () { 107 final Iterator it = super.iterator (); 108 class I implements Iterator { 109 public boolean hasNext() { 110 return it.hasNext (); 111 } 112 113 public Object next() { 114 if (--cnt == 0) { 115 run.run (); 116 } 117 return it.next (); 118 } 119 120 public void remove() { 121 it.remove(); 122 } 123 } 124 return new I (); 125 } 126 } 127 } 128 | Popular Tags |