1

I'd like to pass through an array and make two new arrays: one with the elements that meet a certain condition, and one that does not.

Is this possible in one pass, or will I necessarily have to pass twice: once to determine how big the new arrays should be, and again to fill these arrays? I can see how this would work with another programming language or with a different data structure, but with java this does not seems possible.

5
  • 2
    Just determined not to use a more appropriate data structure like an ArrayList<T>?
    – Kirk Woll
    Mar 9, 2012 at 22:36
  • It definitely would be more appropriate, but I'm wondering if this is even possible with arrays.
    – SN.
    Mar 9, 2012 at 22:37
  • 1
    @SN. It is possible. Just not for a strict definition of "one pass". The two approaches are 1) scan, create appropriate array sizes or 2) create full-sized arrays, process, and shrink (or pass around a "used length" or have another sentinel) to fit. Neither case is ideal, although it likely Just Doesn't Matter (but I second Kirk Woll ;-). This is also precisely why I avoid Java...
    – user166390
    Mar 9, 2012 at 22:40
  • 1
    OT: @pst: you are avoiding java because you can't resize arrays?
    – stryba
    Mar 9, 2012 at 22:45
  • @stryba I avoid Java because of everything it lacks that make dealing with simple collection operations painfully verbose and procedural ;-) Arrays in Java (and even the answer below) showcase this well, I think. For instance, I would much rather do: theList.partition(x => x.length > 5) or similar. (There is a correlation between the ease-of-use-of-collections and my desire to use a particular language.)
    – user166390
    Mar 9, 2012 at 23:04

1 Answer 1

3

You want to use Arrays? Or it may be collection? If so then:

  String[] st = new String[] {"asas", "dsdsdsd", "sfdsfdsf", "dsfsdfdsfdsfs"};
  List<String> s1 = new ArrayList<String>();
  List<String> s2 = new ArrayList<String>();
  for (String s: st) {
      if (s.length>5)
          s1.add(s)
      else
          s2.add(s);
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.