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.

Chris Gerken
16.4k6 gold badges48 silver badges61 bronze badges
asked Mar 9, 2012 at 22:35
5
  • 2
    Just determined not to use a more appropriate data structure like an ArrayList<T>? Commented Mar 9, 2012 at 22:36
  • It definitely would be more appropriate, but I'm wondering if this is even possible with arrays. Commented 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... Commented Mar 9, 2012 at 22:40
  • 1
    OT: @pst: you are avoiding java because you can't resize arrays? Commented 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.) Commented 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);
 }
Adam Mihalcin
14.5k4 gold badges38 silver badges52 bronze badges
answered Mar 9, 2012 at 22:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.