1

I want to return two String arrays from a method(which populates those arrays). Both array are of differnt size from each other. How do I go about ??

String[] namesOfColumnsFound = new String[45];

String[] namesOfColumnsNotFound = new String[25];

Edit : I just need to pass the data.. no behaviour is not needed to be passed

9 Answers 9

6

Create an object that contains both arrays rather than some collection composition. Why ?

  1. it'll make refactoring a lot easier if you change the return composition. You won't have to change instances of List<Array<...>>
  2. you can encapsulate behaviour within that object. Your clients can ask that return object for the first array, the second array etc. Better still, they can ask the return object to do things using those arrays rather than pull them out. That's the essence of OO right there - telling objects to do things for you, rather than ask them to tell you what they're made of.

e.g.

public class ReturnType {
   private Array<String> first = ...
   private Array<String> second = ...

   public boolean isValid() { ... }
   public void doSomethingCleverWithReturnValues() { ... }
}

public ReturnType giveMeTwoArrays() {
   ...
   return new ReturnType(...)
}

It's really tempting to do something simple (such as returning a tuple or a collection composition), but the refactoring pain is sizeable compared to doing the above (I speak from experience having just made this mistake again just now! And that was using Scala - the type inference makes life simpler and it's still a pain)

Sign up to request clarification or add additional context in comments.

1 Comment

i don't understand completely, is there some explanation with some working example pls.
3

Or create a simple wrapper that will contain both arrays.

Example:

class ArrayHelper{
    private String[] strArr1;
    private String[] strArr2; 
    ... [constructor that sets both arrays and getters to access them]
};

2 Comments

can you give an example how to do that for my case ?? Thanks
@Marcos class ArrayHelper{ private String[] strArr1; private String[] strArr2; ... [constructor that sets both arrays and getters to access them] };
2

This is another way of doing

return  (new Object[] { obj1 ,obj2 });

return  Arrays.asList(obj1,obj2);

return (new Object[] { obj1 ,obj2 });

Size of return

class xx
{
public static void main (String[] args)
{   
...
Object[] receiver = m();
System.out.println(receiver.length);  //  size is 2
}
public static Object[] m()
{
String m ="suresh";
return  (new Object[] { m ,new ArrayList().add("PEPE") });
}

2 Comments

what is the size of the list when you create lists like this ?? is it just 2 ??
@Marcos - from javadoc Returns a fixed-size list backed by the specified array - yes, it will be just 2
2

You can return list that has two elements. list[0] would be your first string array, list[1] would be the second.

Comments

1

You can return an array of the two arrays (even if they have not the same length). A List of arrays will work as well. The "cleanest" solution is to use some kind of Tuple type (there was www.javatuples.org , but the server seems to be down right now)

[Edit]

There are several ways to make an array of arrays, e.g.

public int[][] method() {
   int[] array1 = new int[]{1,2,3,4};
   int[] array2 = new int[]{10,20,30};
   int[][] result = new int[]{array1, array2};
   return result;
}

1 Comment

could you give an example of code how to create an array of two arrays ? Thanks.
1

Here are my two cents: I avoid returning language Objects (like String, int, String[], arraylist, map etc) from methods. I believe that what I write should be in business terminology for readability and, more importantly, to relate the code to the problem at hand.

Here is how I would write it (test code):

            ColumnAnalyzer ca = new ColumnAnalyzer();

        ca.analyze();

        System.out.println(ca.getNamesOfColumnsFound().length) ;

        System.out.println(ca.getNamesOfColumnsNotFound().length) ;

The name ColumnAnalyzer and method analyze() should of course be changed to reflect the business system terminology.

Comments

0

You can also return an Object which does contain two arrays, maybe even with some logic how to use the arrays.

Very simple example:

public class Result {
   public String[] array1;
   public String[] array2;
}

Result result = new Result();
result.array1 = xyz;
...

Better would be to put some of the logic concerning array1 and 2 into the Object:

public class Result {
   private String[] array1;
   private String[] array2;
   public Result(String[] array1, String[] array2) {
      this.array1 = array1;
      this.array2 = array2;
   }

   // now some business logic like this, or just return the arrays with getters
   public int getArray1Size() {
   }
}

Comments

0

While this doesn't exactly solve your problem of using two arrays, here's how I would handle it

public Map<String,Boolean> analyzeColumns(SomeStructure struct) {
    Map<String,Boolean> columnName2found = new HashMap<String,Boolean>();
    for(PotentialColumn pc : struct) {
        String name = pc.getName();
        boolean found = pc.isFound();
        columnName2found.put(name,found);
    }
    return columnName2Found;
}


// in action
Map<String,Boolean> columnName2found = anaylzeColumns(struct);

for(Map.Entry<String,Boolean> entry : columnName2found.entrySet()) {
    if(entry.getValue()) handleFound(entry.getKey());
    else handleNotFound(entry.getKey());
}

Comments

0

You could also use a more "generic" wrapper object:

public class Tuple<A, B>{
    private A a;
    private B b;

    public Tuple(A a, B b) {
        this.a = a;
        this.b = b;
    }
    public A getFirst(){return a;}
    public B getSecond(){return b;}
}

Comments

Your Answer

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.