An integer array with a string?

Sockets in my server program are stored in an array of course. I want to attach a string with it in the array
Conceptually like this:
public static OutputStream usr [] = new OutputStream[6], "name" ;
So i can track their login names with their sockets. By association. Calling an array slot would somehow return the integer and the string name.
Can anyone help me out? Thanks

class conn{
      OutputStream out;
      String name;
public static conn usr [] = new conn[6];
for(int i = 0; i < conn.length; i++ )
      conn[ i ] = new conn( myOutputStream, "My String" );
}You should declare a class that can holds any number of members, modify the code to meet your needs
GoodLuck
Mohammed Saleem

Similar Messages

  • Arrays with a string index

    Hi, I am looking for the best way to map a value to a string in an array.
    In PHP this is easy because it supports arrays with string Indexes. For example:
    $array['Canada'] = 5;
    $array['USA'] = 3;
    In Java I can't do this because I can only use an integer to index an array.
    My current solution is to create a two dimensional array:
    array[0][0] = "Canada";
    array[0][1] = 5;
    array[0][0] = "USA";
    array[0][1] = 3;
    I am wondering if there is something better.

    It creates 20 slots for reference variables that can point to Date objects. The references variables are all initialized to null.
    If you do dates[0] = new Date();, that creates a new Date object and points the reference variable in slot 0 at it.
    Date[] dates = new Date[3]; creates 3 slots--0, 1, 2.
    Edited by: jverd on Nov 8, 2007 7:39 PM

  • How to filter an array with a string value

    I want to filter out all Strings in an array that don't have a certain value in them aka. I want only to see values that start with b or bi or bit etc...
    How can I accomplish this?
    Thanks

    This is another one of those things where I'm surprised it's not in the JDK. It's needed sufficiently frequently, and other languages (esp. scripting languages) seem to support this thing commonly.
    Anyway...when I need something like this (that seems as though many others need it as well and it ought to be in the JDK but isn't), the first thing I do is check Apache Jakarta Commons to see if someone has already written such a thing in a reasonably well-supported toolkit. It's worth a look.

  • 2 parts: 1) integer array to string 2) string out to a jTextField

    I am completely new to Java and Netbeans, but I'm writing my 1st
    application that takes a "hex" character input from a jTextField,
    then converts it to an "binary" integer array. I then do a lot of bit
    manipulation, and generate a new "binary" integer array.
    String myhex = jTextField1.getText();
        int len = myhex.length();
        int[] binarray = new int[len*4];
            for (int i = 0; i < len; i++) {
               if (myhex.charAt(i) == '0'){
                  binarray[4*i]=0;
                  binarray[4*i+1]=0;
                  binarray[4*i+2]=0;
                  binarray[4*i+3]=0;
               else if (myhex.charAt(i) ==
               // repeat for '1 to 9' and 'a-f/A-F'
               // generate new integer array(s) using various bits from binarrayI realize it might not be the best way to do the
    conversion, but my input can be of arbitrary length,
    and it is my first time trying to write Java code.
    All of the above I've completed and it works...(thanks Netbeans
    for making the gui interface design a real breeze!)
    So I end up with:
    binarray[0]=0 or 1
    binarray[1]=0 or 1
    binarray[2]=0 or 1
    binarray[n]=0 or 1
    Where n can be any number from 0 to 63...
    I then manipulate the bits in binarray creating a new integer array
    and for the sake of expediency let's call it "newbinarray".
    newbinarray[0]=0 or 1
    newbinarray[1]=0 or 1
    newbinarray[2]=0 or 1
    newbinarray[n]=0 or 1
    Where n can be any number from 0 to 63...
    I first need to know how to convert this "newbinarray" integer array to a string.
    In the simplest terms if the first three elements of the array are [0][1][1],
    I want the string to be 011.
    Then I want to take this newly formed string and output it to a jTextField.
    string 011 output in JTextField as 011
    I've scoured the net, and I've seen a lot of complex answers involving
    formatting, but I'm looking for just a simple answer here so I can finish
    this application as quickly as possible.
    Thanks,
    Thorne Kontos

    Here's an example, not using NetBeans:
    import javax.swing.*;
    public class TextDemo extends JPanel
        public TextDemo()
            int[] newbinarray = {0, 1, 1};
            StringBuffer sb = new StringBuffer();
            for (int value : newbinarray)
                sb.append(value);
            String st = new String(sb);
            this.add(new JTextField(st));
        private static void createAndShowGUI()
            JFrame frame = new JFrame("TextDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new TextDemo());
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
    }

  • How to bind SelectManyChoice to Integer array parameter

    Hi.
    I am using JDev TP4. I need to populate an integer array with the keys of the items selected in a SelectManyChoice.
    I have created a page with a parameter form for the three parameters and a readonly table for the result class from a data control for this method:
    public FreeGuaranteeModel[] getFreeGuarantees(Timestamp firstDate, Timestamp lastDate, Integer[] companyIds)
    In the parameter form i have created a SelectManyChoice which displays a list
    from a viewObject by dragging the companyIds parameter onto the parameter form, creating a SelectSingle component and then converted it to a SelectManyChoice.
    The page renders ok, I can select one or more items in the list, but when I press the button to execute the method, the companyIds array is empty.
    (The two date parameters are populated).
    What am I missing? Is the binding wrong? I am new to JDev so if there is some other way to do this, please let me know.
    This is the relevant part of the jspx:
    <af:selectManyChoice value="#{bindings.companyIds.inputValue}"
              label="#{bindings.companyIds.label}"
              shortDesc="#{bindings.companyIds.hints.tooltip}"
              binding="#{backing_ViewFinancialResult.selectOneListbox1}"
              id="selectOneListbox1">
    <f:selectItems value="#{bindings.companyIds.items}"
         binding="#{backing_ViewFinancialResult.selectItems1}"
         id="selectItems1"/>
    </af:selectManyChoice>
    The pagedef contains this:
    <?xml version="1.0" encoding="UTF-8" ?>
    <pageDefinition xmlns="http://xmlns.oracle.com/adfm/uimodel"
    version="11.1.1.49.49" id="ViewFinancialResultPageDef"
    Package="com.ispartner.gvg.pageDefs">
    <parameters/>
    <executables>
    <variableIterator id="variables">
    <variable Type="java.sql.Timestamp" Name="getFreeGuarantees_firstDate"
    IsQueriable="false"/>
    <variable Type="java.sql.Timestamp" Name="getFreeGuarantees_lastDate"
    IsQueriable="false"/>
    <variable Type="java.lang.Integer[]" Name="getFreeGuarantees_companyIds"
    IsQueriable="false"/>
    </variableIterator>
    <methodIterator Binds="getFreeGuarantees.result"
    DataControl="CapacityReader" RangeSize="25"
    BeanClass="com.ispartner.gvg.util.capacity.FreeGuaranteeModel"
    id="getFreeGuaranteesIterator"
    RefreshCondition="#{adfFacesContext.postback == true}"
    Refresh="renderModelIfNeeded"/>
    <iterator Binds="CompanyLOV1" RangeSize="-1"
    DataControl="ChoiceListAMDataControl" id="CompanyLOV1Iterator"/>
    </executables>
    <bindings>
    <methodAction id="getFreeGuarantees" RequiresUpdateModel="true"
    Action="invokeMethod" MethodName="getFreeGuarantees"
    IsViewObjectMethod="false" DataControl="CapacityReader"
    InstanceName="CapacityReader.dataProvider"
    ReturnName="CapacityReader.methodResults.getFreeGuarantees_CapacityReader_dataProvider_getFreeGuarantees_result">
    <NamedData NDName="firstDate" NDType="java.sql.Timestamp"
    NDValue="${getFreeGuarantees_firstDate}"/>
    <NamedData NDName="lastDate" NDType="java.sql.Timestamp"
    NDValue="${getFreeGuarantees_lastDate}"/>
    <NamedData NDName="companyIds" NDType="java.lang.Integer[]"
    NDValue="${bindings.getFreeGuarantees_companyIds}"/>
    </methodAction>
    <attributeValues IterBinding="variables" id="firstDate">
    <AttrNames>
    <Item Value="getFreeGuarantees_firstDate"/>
    </AttrNames>
    </attributeValues>
    <attributeValues IterBinding="variables" id="lastDate">
    <AttrNames>
    <Item Value="getFreeGuarantees_lastDate"/>
    </AttrNames>
    </attributeValues>
    <tree IterBinding="getFreeGuaranteesIterator" id="FreeGuaranteeModel">
    <nodeDefinition DefName="com.ispartner.gvg.util.capacity.FreeGuaranteeModel">
    <AttrNames>
    <Item Value="companyId"/>
    <Item Value="name"/>
    <Item Value="guaranteeRequired"/>
    <Item Value="guaranteeToDate"/>
    <Item Value="guaranteeAmount"/>
    <Item Value="bookedValue"/>
    <Item Value="freeGuarantee"/>
    </AttrNames>
    </nodeDefinition>
    </tree>
    <list IterBinding="variables" id="companyIds" DTSupportsMRU="false"
    StaticList="false" ListIter="CompanyLOV1Iterator"
    NullValueFlag="start" NullValueId="companyIds_null">
    <AttrNames>
    <Item Value="getFreeGuarantees_companyIds"/>
    </AttrNames>
    <ListAttrNames>
    <Item Value="CompanyId"/>
    </ListAttrNames>
    <ListDisplayAttrNames>
    <Item Value="ShortName"/>
    </ListDisplayAttrNames>
    </list>
    </bindings>
    <ResourceBundle>
    <PropertiesBundle xmlns="http://xmlns.oracle.com/adfm/resourcebundle"
    PropertiesFile="com.ispartner.gvg.gvg-webBundle"/>
    </ResourceBundle>
    </pageDefinition>
    Regards,
    TL

    Hi,
    Thank you for your answer.
    Following the example I was able to get the selected entries into an Integer array property with accessors which I created in a managed bean.
    But I have not been able to get the values into the companyIds parameter of the method to execute.
    Is there a way to bind directly to this parameter, or do I have to collect all parameters through separate properties and then call my method manually when the button is pressed?
    TL

  • Having trouble converting array to spreadsheet string, storing the file and coverting back to array with complex numbers

    I am working with a network analyzer. I have arrays made of 5 columns the first consisting of an integer and the next four consisting of complex numbers. I am converting the array into a spreadsheet string and then saving the file using the write characters to a file VI. That seems to work well as when I open the file in Excel all the data is there. However when I try to reverse the process, open file and convert back to array, I loose some of the data. Specifically the imaginary parts of my complex numbers are all going to zero. I have narrowed down the problem to be in the conversion from spreadsheet string to array and vice versa. I
    think the problem may be with the 'format' input to the VI. I do not have an adequate resource for this so I am not sure what to put in to accomplish my task. Any takers?

    Hi Biz
    I don't think there is a direct way of converting a complex number to a
    string, so when you convert the array to a spreadsheet string, the
    numbers would be converted to real data.
    However, you could try separating the real and imaginary parts using the
    "Numeric: Complex to Re/Im" function, and then store these - either in
    separate files or in adjacent columns/rows in the same file. Then, when
    you read in the data again, use the "Numeric: Re/Im to Complex" function
    to put the two "halves" together.
    If you actually want Excel to interpret the numbers as imaginary, then
    you'll probably want to create a string for each complex number of the
    form "Re + Im*i" (after separating the Re and Im parts), by using
    "String:Format into String" with 2 numeric inputs and the format string
    "%f+%fi".
    Reading the data back into Labview then would require splitting the
    string into the 2 pieces by using "Stringcan from String" with 2
    numeric outputs (smae precision as original numbers specified by the 2
    Default Value inputs) and the same format string "%f+%fi", and then using
    the above-mentioned "Numeric: Re/Im to Complex" function. It worked for
    me, so if you can't follow what I am describing, send me an email and I
    can email you what I did (LV 5.1.1).
    Paul
    Biz wrote:
    > Having trouble converting array to spreadsheet string, storing the
    > file and coverting back to array with complex numbers
    >
    > I am working with a network analyzer. I have arrays made of 5 columns
    > the first consisting of an integer and the next four consisting of
    > complex numbers. I am converting the array into a spreadsheet string
    > and then saving the file using the write characters to a file VI. That
    > seems to work well as when I open the file in Excel all the data is
    > there. However when I try to reverse the process, open file and
    > convert back to array, I loose some of the data. Specifically the
    > imaginary parts of my complex numbers are all going to zero. I have
    > narrowed down the problem to be in the conversion from spreadsheet
    > string to array and vice versa. I think the problem may be with the
    > 'format' input to the VI. I do not have an adequate resource for this
    > so I am not sure what to put in to accomplish my task. Any takers?
    Research Assistant
    School of Physiotherapy, Curtin University of Technology
    Selby Street, Shenton Park, Western Australia, Australia. 6008
    email: [email protected]
    Tel. +61 8 9266 4657 Fax. +61 8 9266 3699
    "Everyone who calls on the name of the Lord will be saved." Romans 10:12
    "For all have sinned and fall short of the glory of God, and are
    justified freely by his grace through the redemption that came by Christ
    Jesus." Romans 3:23-4

  • Trouble with array to spreadsheet string

    I am having trouble with the array to spreadsheet string.
    I have a 1-d array of string, the output spreadsheet string never puts a space on the first row, but all others.
    example:
    05:59:29.170    00000101     8        00 00 07 00 0B 0E 0D 0C
     05:59:29.198    00000100     8        00 00 3A 3A 39 39 39 39
     05:59:29.220    00000101     8        00 00 07 00 0B 0E 0D 0C
     05:59:29.248    00000100     8        00 00 39 39 39 39 39 39
    format string is %s and default tab is delimiter.
    this is screwing up my program because of the "scan for string" function can't be used correctly if the spreadsheet string isnt consistent.
    Any suggestions?
    Thanks

    You don't need to use "array to spreadheet string": You could use plain formatting for full control over the output.
    Still, your observation is a bit odd. Could you attach a simple VI that shows the behavior? (Put your input array into a diagram constant).
    LabVIEW Champion . Do more with less code and in less time .

  • Converting a string to an integer array

    This is kind of a newbie question, but:
    If I have a string which looks like this: "12,54,253,64"
    what is the most effective/elegant/best/etc. way to convert it into an integer array (of course not including the ","s :-)
    Any suggestions are greatly appreciated.

    Thanks, I'll do that. I was looking at StringTokenizer and other things, but it seems they are not implemented in j2me?

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • Sending (String/Bean) Arrays with Webservices and DII

    I'm using the application server from the Sun J2EE SDK (J2EE(TM) Application Server 1.4 Developer Release (build b44-dr) and I'm trying to get an array with Beans or Strings to be send to an Dynamic Invocation Client.
    Can someone point me to an example or send one to me, I'm really stuck with it.

    Can nobody point me to an example how to send arrays with a webservice to a Dynamic Interface Invocation Client???

  • How do i convert a double array (with spaces and tabs) to a string?

    Hi
    In our files, we have a mixture of spaces and tabs as a delimeter. How do I convert a double array into a string?
    Thank you.

    Not sure about the last part of your question.
    The Search and Replace pattern can be better than the simple Search and Replace string when you have to do complex searchs, such as detecting multiple spaces.
    Have a look at the attachment.
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    ReplaceSpaces.vi ‏27 KB

  • Saving an integer array into a .txt file

    hii, im only a beginner in java, so this is the only code i've learned so far for saving array elements into a file
         public static void saveNames(String [] name) throws IOException
                   FileWriter file = new FileWriter("Example\\names.txt");
                   BufferedWriter out = new BufferedWriter(file);
                   int i = 0;
                   while (i < name.length)
                             if (name[i] != null)
                                  out.write(name);
                                  out.newLine();
                                  i++;
                   out.flush();
                   out.close();
    However, this is only used for string arrays; and i can't call the same method for an integer array (because it's not compatible with null)
    I don't really understand this code either... since my teacher actually just gave us the code to use, and didn't really explain how it works
    I have the same problem for my reading a file code as well --> it's only compatible with string
         public static String [] readNames (String [] name) throws IOException
              int x = 0;
              int counter = 0;
              String temp = "asdf";
              name = new String [100];
              FileReader file = new FileReader("Example\\names.txt");
              BufferedReader in = new BufferedReader(file);
              int i = 0;
              while (i < array.length && temp != null)                    // while the end of file is not reached
                   temp = in.readLine();
                   if (temp != null)
                        name[i] = temp;                    // saves temp into the array
                   else
                        name[i] = "";
                   i++;
              in.close();                                   // close the file
              return name;
    Could someone suggest a way to save elements from an integer array to a file, and read integer elements of that file?
    Or if it's possible, replace null with a similar variable (function?), that is suitable for the integer array (i can't use temp != 0 because some of my elements might be 0)
    Thanks so much!!!!!

    because it's not compatible with nullI think it should be okay to just remove the null condition check since there are no null elements in a primitive array when writing.
    Use Integer.parseInt() [http://java.sun.com/javase/6/docs/api/java/lang/Integer.html] to convert the String into an Integer when you read it back and use Integer.toString() to be able to write it as a String.

  • Multi-dimensional arrays with non-specified dimension

    Hi all,
    I'm trying to write a method to create a multi-dimensional array of
    Integer, based on another one, taken as parameter. I would like the
    method to work for an array of a non-specified dimension, that is,
    it could take as parameter a Integer[], or a Integer[][], or a
    Integer[][][] and so on.
    The idea is to have as a result an array with the original elements
    doubled.
    Here is my recursive function:
        public static Object[] f(Object[] a) {
             // the array to be returned is created with the
             // same size as the original
            Object[] r = new Object[a.length];
            for (int i=0; i<a.length; i++) {
                Object elem = a;
    Object newElem = null;
    if (elem instanceof Object[]) {
    // Recursive case
    newElem = f((Object[]) elem);
    } else if (elem instanceof Integer) {
    // Base case
    newElem = new Integer(((Integer)elem).intValue() * 2);
    r[i] = newElem;
    return r;
    This method returns an array with the same structure (that is, same
    dimensions) of the array taken in the constructor. In the recursive
    case, it just calls the function to the inner arrays. In the base
    case, where I have an Integer, it creates a new Integer, whose
    value is the old multiplied by 2.
    Then I initialize an array:
        public static void main(String args[]) throws Exception {
            Integer[][] a = new Integer[][] {
                new Integer[] {
                    new Integer(0), new Integer(2)
                new Integer[] {
                    new Integer(1), new Integer(4), new Integer(3)
      // And try to call the function like this:
            Integer [][] b = (Integer [][]) f(a);
        }   And I get a java.lang.ClassCastException: [Ljava.lang.Object;
    I don't understand the reason of this exception, because the
    object returned is a Integer[][]. Isn't it?
    And since I don't have a compiler error in the cast, that means
    that Object[] and Integer[][] are not inconvertible. Right?
    Could anyone explain me why this is wrong and/or give me some
    ideas to do what I'm trying to do?
    Thanks a lot,
    Angela

    I retract my previous statement about using
    reflection. Use "Object[] r =(Object[])a.clone()"
    to create a new array of the same type.You don't need temporary array variable here.
    You could simply use argument a instead of r.
    (But this my gotcha is derived from your clever rep.)Well, this isn't a temporary variable, its the return variable, which is different. If you don't want the original matrix changed, you have to clone the argument.

  • I want to create a an Array with Hex pointers!!

    Hi all,
    I want to create an array that uses Hex as addresses, so that if I want to call on the 16th array element I wouldn't use array[15] but would use array[F] instead, and if I want the 18th element it would be array[11]. Is there any good way of doing that?

    They're just numbers. You increment them by adding one to them...
        int x = 0x43AF;
        int y = 232 + x;
        int z = 0x9A + 0x10B + 4 + 5 - 0x88FEF;
        int a = x + y;
        z ++;
        a += y;
        x += (0x9F9F - 55 * y);They could be bytes, too, or they could be longs, shorts, or chars. It's just a different way to type constants. The way you create your array isn't any different than normal, nor is the way you treat the numbers. The primitive data types that can support those numbers doesn't change either... they're just integers, but with a different notation.
    As far as converting an integer to a hexadecimal String, you can use the appropriate wrapper object's toHexString method:
        int x = 0xBEEF; // doesn't matter if you type 0xBEEF or 48879 or 0137357
        System.out.println("x = " + x + " decimal");
        System.out.println("x = " + Integer.toHexString(x) + " hex");
        System.out.println("x = " + Integer.toBinaryString(x) + " binary");
        System.out.println("x = " + Integer.toOctalString(x) + " octal");If you want to parse a hexadecimal string that the user enters, use the parseXXX method in the appropriate wrapper class. Keep in mind that, for hexadecimal numbers, these methods will get confused by a "0x" at the beginning. So, if you are converting a String to an integer using base 16, you'll have to make sure you strip off the "0x" at the beginning if there is one.
        int x = Integer.parseInt("BEEF", 16);
        int y = Integer.parseInt("48879", 10); // '10' is optional here
        int z = Integer.parseInt("137357", 8);
        int a = Integer.parseInt("1011111011101111", 2);x, y, z, and a should all end up with the same value if I did the conversions right.
    Go to http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48298 and read section 3.10.
    Jason

  • Fill Array with all possible combinations of 0/1

    Hi,
    i'm looking for a fast way to fill an array, respectively an int[8], with all possible combinations of 0 and 1 (or -1 and 1, shouldn't make a difference).
    I kind of know how to do it using multiple loops but I assume there is a more elegant or at leaster "better" practice.
    Thanks,
    nikolaus
            static int cnt = 0;
         public static void main(String[] args) {
              int[] element = new int[]{1,1,1,1,1,1,1,1};
              Integer[] x = new Integer[2];
              x[0] = 1;
              x[1] = -1;
              for(int i7:x){
                   element[7] = i7;
                   for(int i6:x){
                        element[6] = i6;
                        for(int i5:x){
                             element[5] = i5;
                             for(int i4:x){
                                  element[4] = i4;
                                  for(int i3:x){
                                       element[3] = i3;
                                       for(int i2:x){
                                            element[2] = i2;
                                            for(int i1:x){
                                                 element[1] = i1;
                                                 for(int i0:x){
                                                      element[0] = i0;
                                                      cnt++;
              }Edited by: NikolausO on Oct 30, 2008 4:21 AM
    Edited by: NikolausO on Oct 30, 2008 4:22 AM

    pm_kirkham wrote:
    No I replied to message number 5. as the ' (In reply to #5 )' above my post indicates, which was in reply to (a reply) to Sabre150's post which wasn't using enhanced loops, nor has any obvious place where you could use that approach to fill the array.
    Though you could pass in an array of the values to fill the array with, and loop over those, instead of using 0 or 1, at which point Sabre's approach becomes the same as your OP, but without the manual unrolling:
    import java.util.Arrays;
    public class NaryCombinations {
    public interface CombinationHandler {
    void apply (int[] combination) ;
    public static void main(String[] args) {
    calculateCombinations(new int[]{-1, 0, 1}, 4, new CombinationHandler () {
    public void apply (int[] combination) {
    System.out.println(Arrays.toString(combination));
    public static void calculateCombinations (int[] values, int depth, CombinationHandler handler) {
    recursivelyCalculateCombinations(values, 0, depth, handler, new int[depth]);
    private static void recursivelyCalculateCombinations (int[] values, int index, int depth,
    CombinationHandler handler, int[] combination) {
    if (index == depth) {
    handler.apply(combination);
    } else {
    for (int value : values) {
    combination[index] = value;
    recursivelyCalculateCombinations(values, index + 1, depth, handler, combination);
    Which looks to use the same basic approach to the generalization I created shortly after posting the original.
    public class Scratch1
         * A 'callback' to be invoked with every combination
         * of the result.
        public interface Callback
             * Invoked for each combination.
             * <br>
             * Each call is passed an new instance of the array.
             * @param array the array containing a combination.
            void processArray(int[] array);
        public Scratch1(final int[] array, final Callback callback, final int... values)
            if (callback == null)
                throw new IllegalArgumentException("The 'callback' cannot be 'null'");
            if (array.length < 1)
                throw new IllegalArgumentException("The array length must be >= 1");
            if ((values == null) || (values.length < 1))
                throw new IllegalArgumentException("The 'values' must have be at least of length 2");
            callback_ = callback;
            values_ = values.clone();
            array_ = array;
        public Scratch1(final int order, final Callback callback, final int... values)
            this(new int[order], callback, values);
         * Generates every possible value and invokes the callback for each one.
        public void process()
            process(0);
         * Internal method with no logical external use.
        private void process(int n)
            if (n == array_.length)
                callback_.processArray(array_.clone());
            else
                for (int v : values_)
                    array_[n] = v;
                    process(n + 1);
        private final Callback callback_;
        private final int[] values_;
        private final int[] array_;
        public static void main(String[] args) throws Exception
            final Callback callback = new Callback()
                public void processArray(int[] array)
                    System.out.println(java.util.Arrays.toString(array));
            new Scratch1(6, callback, 2, 1, 0).process();

Maybe you are looking for

  • How can I change a page position in a large document?,

    How can I change a page position in a large document?

  • Getting Process Instance Information and Task Properties in a process

    Iam using WebLogic8.1 Integration BPM feature. I've designed a Worklist based application. In the business process, i've to call a java class method from the business process which takes the process instance and task related properties (viz. the task

  • Changes in database:-

    Hi all, I need to check if some DDL has occured (only on tablepaces) from last few days. Does anyone know where I can find the infomation: For example: if TEMP tablepace has been deleted and recreated last week. where I can get info about the new TEM

  • HTTP Transformation using POST Method

    Hi, I will have to use POST method with header as application/json to get the results in http transformation. I downloaded the RESTFUL client utility from Chrome, to see how JSON would look like by passing parameters and the result is displayed as ex

  • How to repeat data in a recordset?

    I have just tested a recordset joining 3 tables , store_items, store_colour and store_size. I have put them onto the page and set a repeat region showing all items in the database with product sizes and colours available. However for example T-shirts