Hi,

I've spent some time today using JRuby to inspect data I get back from EJB's, and I soon got mad about having to use get(0) or iterator.next to get at elements.

So, the attached patch makes it possible to use [] and []= for Maps and Lists, and makes <<, + and - available for all Collection's. For me, this makes Java integration MUCH more useable.

Regards
 Ola Bini
Index: src/builtin/java/collections.rb
===================================================================
RCS file: /cvsroot/jruby/jruby/src/builtin/java/collections.rb,v
retrieving revision 1.4
diff -u -r1.4 collections.rb
--- src/builtin/java/collections.rb     17 Oct 2005 15:02:04 -0000      1.4
+++ src/builtin/java/collections.rb     14 Jun 2006 13:02:17 -0000
@@ -3,6 +3,13 @@
   def each(&block)
     entrySet.each { |pair| block.call(pair.key, pair.value) }
   end
+  def [](key)
+    get(key)
+  end
+  def []=(key,val)
+    put(key,val)
+    val
+  end
 }
   
 JavaUtilities.extend_proxy('java.util.Set') {
@@ -21,6 +28,21 @@
   end
 }
 
+JavaUtilities.extend_proxy('java.util.Collection') { 
+  def <<(a); add(a); self; end
+  def +(oth)
+    nw = self.dup
+    nw.addAll(oth)
+    nw
+  end
+  def -(oth)
+    nw = self.dup
+    nw.removeAll(oth)
+    nw
+  end
+}
+
+
 JavaUtilities.extend_proxy('java.util.List') {
   include Enumerable
 
@@ -29,7 +51,20 @@
 #      0.upto(size-1) { |index| block.call(get(index)) }
     0.upto(size-1) { |index| yield(get(index)) }
   end
-  def <<(a); add(a); end
+  def [](ix)
+    if ix < size
+      get(ix)
+    else
+      nil
+    end
+  end
+  def []=(ix,val)
+    if size < ix
+      ((ix-size)+1).times { self << nil }
+    end
+    set(ix,val)
+    val
+  end
   def sort()
     include_class 'java.util.ArrayList'
     include_class 'java.util.Collections'
@@ -76,4 +111,4 @@
     p = yield(*args)
     p p
   end
-}
\ No newline at end of file
+}
_______________________________________________
Jruby-devel mailing list
Jruby-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/jruby-devel

Reply via email to