Loading...
Logo
Processing Forum
I've made a class. Then later i realized that the ideal input for my constructor should be different than the one that i have now, like:

i made:

Constructor( String _s, int[] i)
{
      // A lot of code goes here
}



now i want:

Constructor( String _s, ArrayList<Integer> i)
{
      // can i just convert the list to array and call the old constructor here?
      // How?
      // i dont want to repeat the code unnecessarily
}

I think in doing this way to get more flexible and dont have to change the inplementation of first constructor. Of course i can convert those in draw before "feeding" the constructor. Would that be a better choice?

thanks





Replies(4)

It would probably be best to either a. Change the constructor to work with ArrayLists or b. Change your draw() code use an array. Alternatively (and perhaps a better solution), you could move all of the constructor code out of the constructor and into a separate function; then, from the constructor, call the function. In another constructor, change the ArrayList to an array and call the function. See as follows:

Copy code
  1. //Untested
  2. class Example {
  3.   //Stuff
  4.  
  5.   Example(String s, int[] i) {
  6.     initFuntion(s, i);
  7.   }
  8.  
  9.   Example(String s, ArrayList[Integer] i) {
  10.     int[] array = new int[i.size()];
  11.     for(int j = 0; j < i.size(); j ++)
  12.       array[j] = i.get(j);
  13.    
  14.     initFunction(s, array);
  15.   }
  16.  
  17.   void initFunction(String s, int[] i) {
  18.     //Init code
  19.   }
  20. }
Thanks calsign. Good to know. I found that I'll have to change more than i thought before. Simplifying the constructor  and a lot of stuff in the class, I have to change the way thing was done since i found a library that is going to provide me with different wrap of the data. Any way, as i said, it is good to know. :-)
For the record, you can use this() to call another constructor, but it must be the first instruction of the new constructor, which isn't possible with your need.
Now, if the first constructor used an array of Integer, it would have been easier:
Copy code
  1. class Example
  2. {
  3.   Example(String s, Integer[] ints)
  4.   {
  5.     println(ints);
  6.   }
  7.  
  8.   Example(String s, ArrayList<Integer> lints)
  9.   {
  10.     this(s, lints.toArray(new Integer[lints.size()]));
  11.   }
  12. }

  13. void setup()
  14. {
  15.   ArrayList<Integer> list = new ArrayList<Integer>();
  16.   list.add(5); list.add(42);
  17.   Example ex = new Example("x", list);
  18. }