• Post Reply Bookmark Topic Watch Topic
  • New Topic

Iterating over sets of sets  RSS feed

 
Tom Brodhead
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm trying to construct an algorithm for iterating over sets and their subsets, so as a simple case I constructed the following scenario:



"d" stores the sets a, b, and c. When I iterate over d, I can in fact establish that d[i] is an array, but I can't retrieve its length or access it as an array for further operations.

I'm trying not to rely on built-it, higher-level facilities in Java; what am I doing wrong here, and is there a better way to store sets of sets of sets, etc.?

~~Tom
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although a, b & c are arrays, you're storing them as plain objects (which is allowed, as arrays are objects). So you've got two options here:

1. Declare d as an Object[][] - an array of arrays. That way you could access d[i].length directly. And you wouldn't even have to check if it was an array. But you'd only be able to put arrays into it - you'd lose that flexibility.

2. Cast d[i] to an Object[]. Once you've done that you can treat is as an array. For example:

One final thing though - all this is using arrays. In the majority of cases, you're better off using the various collection classes in java.util.
 
Anooj Narvekar
Greenhorn
Posts: 10
IntelliJ IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alternately, you could do the following:
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anooj Narvekar wrote:Alternately, you could do the following:

How is that "alternatively"? It's exactly the same approach! (without the mistyped semi-colon that I've just fixed )
 
Anooj Narvekar
Greenhorn
Posts: 10
IntelliJ IDE Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well "Alternately" cause my snippet is not using an Array of arrays. Looks simple with straight forward type-casting.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which was the second of my approaches, and the only one I'd given a code example of.
 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More succinctly:

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!